gpt4 book ai didi

WCF Windows 服务作为预定服务

转载 作者:行者123 更新时间:2023-12-02 06:12:30 24 4
gpt4 key购买 nike

我有一个在应用服务器上运行的 .net WCF Windows 服务,该服务持续监视文件夹中的 xml 文件。如何让此服务仅在每天的特定时间(凌晨 1 点)运行?

谢谢。

最佳答案

您的服务是真正的服务还是只是监视 XML 文件夹的 WCF 应用程序?

如果您的 WCF 服务只是一个普通的应用程序,最简单的方法是使用 Windows 中的计划任务功能(位于控制面板中)。只需让应用程序在启动时检查文件夹并设置计划任务,以便在您需要的任何时间启动应用程序。

如果目标应用程序是真正的 Windows 服务,则需要使用内部计时器。查看 System.Timers.Timer 类。

public void OnLoad() {
Timer timer = new Timer();

// Add event handler
timer.Elapsed += WorkMethod;

// Give us more control over the timer.
timer.AutoReset = false;

SetupTimer(timer);
}

// Setups the timer for the next interval and starts it.
private void SetupTimer(Timer timer) {
timer.Interval = GetNextChecktime().Subtract(DateTime.Now).TotalMillisecond;

timer.Start();
}

private void WorkMethod(object sender, EventArgs e) {
// Do work here

// Setup the timer for the next cycle.
SetupTimer((Timer)sender);
}

private DateTime GetNextChecktime() {
// Return the next time the service should run as a datetime.
}

使用 SetupTimer 而不是仅使用自动重复的 AutoReset = true 的原因是为了使计时器与 GetNextChecktime() 同步。仅使用 24*60*60*1000 毫秒作为经过的计时器将给出 24 小时阶段,但您需要在 01:00 启动脚本才能使其每天 01:00 运行。

如果您仍然可以影响应用程序的运行方式,我实际上会推荐第一种方法。除非您在服务中有更多功能或需要维护一些持久状态,否则只拥有一个在启动时监视文件夹然后退出的应用程序会更简单。由于计划由 Windows 完成,因此更易于调试且不易出错。

关于WCF Windows 服务作为预定服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/789852/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com