Windows服务的计划执行在重新启动后延迟

时间:2015-07-24 06:18:17

标签: c# windows-services

我创建了一个Windows服务,计划在特定时间每天运行。我在其中使用了计时器。它运行成功。

为了测试服务,我将间隔减少到5分钟并且每隔5分钟运行一次,但是一个问题是当我在定时器间隔之间重新启动系统时它会在额外的23秒后执行想想系统重启的时间。例如,检查日志文件。

它应该在完全独立于系统重启后的5分钟后执行。我该怎么做?

我尝试查找,但多数解决方案与自动延迟启动类型有关。

提前致谢。

这些是日志文件条目:     另一篇文章于24-Jul-15 11:02:00 AM     另一篇文章于24-Jul-15 11:07:00 AM     另一个参赛作品于7月24日至11月12日上午12点12分     另一个条目是24-Jul-15 11:17:00 AM //系统重启
    另一个条目是在7月24日星期五上午11:22:23 //系统重启
    在7月24日星期五上午11:27:47再次进入     在7月24日星期五上午11:32:47的另一个条目
    另一个条目是在7月24日 - 星期五11:37:47

以下是代码:

public partial class ScheduledService : ServiceBase
{
    Timer timer = new Timer();
    DateTime today;// = new DateTime();
    DateTime yesterday;
    public ScheduledService()
    {
        InitializeComponent();
        today = new DateTime();
        today = DateTime.Today;

        TimeSpan ts = new TimeSpan(11, 02, 0);
        today = today.Date + ts;

        yesterday = new DateTime();
        yesterday = today.AddDays(-1);
    } 

    protected override void OnStart(string[] args)
    {
        //add this line to text file during start of service  
        TraceService1("start service at:" + DateTime.Now);

        //handle Elapsed event
        timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);

        //This statement is used to set interval to 1 minute (= 60,000 milliseconds)     

        timer.Interval = today.Subtract(DateTime.Now).TotalSeconds * 1000;

        //enabling the timer
        timer.Enabled = true;
    }   

    protected override void OnStop()
    {
        timer.Enabled = false;
        TraceService1("stopping service at:" + DateTime.Now); //

    }
    private void OnElapsedTime(object source, ElapsedEventArgs e)
    {
        TraceService("Another entry at " + DateTime.Now); 

        if (timer.Interval != 5 * 60 * 1000)//86400000
        {
            timer.Interval = 5 * 60 * 1000;
        } 
    }
}

0 个答案:

没有答案