WCF Windows服务作为计划服务

Ste*_*man 2 wcf windows-services

我有一个在应用服务器上运行的.net WCF Windows服务,它继续监视xml文件的文件夹.如何在每天的特定时间(01.00小时)运行此服务?

谢谢.

Mik*_*nen 9

您的服务是真实服务还是仅监视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.
}
Run Code Online (Sandbox Code Playgroud)

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

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