WCF windows service 作为定时服务 [英] WCF windows service as scheduled service

查看:34
本文介绍了WCF windows service 作为定时服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在应用服务器上运行的 .net WCF Windows 服务,该服务一直监视文件夹中的 xml 文件.如何让此服务仅在每天的特定时间(01:00)运行?

I've a .net WCF windows service running on an app server which keeps monitoring a folder for xml files. How do I make this service run only at a particular time (01.00 hours) everyday ?

谢谢.

推荐答案

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

Is your service a real service or just a WCF application which monitors the XML folder?

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

In case your WCF service is just a normal application the easiest way is to use the Scheduled Tasks functionality in Windows (Found in Control Panel). Just have the application check the folder on startup and set a scheduled task which starts the application at whatever time you want.

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

If the target application is a real Windows Service, you need to use an internal timer. Have a look at the System.Timers.Timer class.

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 运行.

The reason for using SetupTimer instead of just using AutoReset = true which would repeat automatically is to synchronize the timer with the GetNextChecktime(). Just using 24*60*60*1000 milliseconds as the elapsed timer would give 24 hour phase but you'd need to start the script at 01:00 to have it run daily at 01:00.

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

If you can still affect the way the application is run, I'd actually recommend the first method. Unless you have more functionality in the service or need to maintain some persistent state it's simpler to just have an application which monitors the folder on startup and then exits. It's also easier to debug and less error prone as the scheduling is done by Windows.

这篇关于WCF windows service 作为定时服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆