首页 > 解决方案 > 安排 Windows 服务在每天凌晨 3:00 运行

问题描述

protected override void OnStart(string[] args)
{
    aTimer = new Timer();
    var timer = System.Configuration.ConfigurationManager.AppSettings["Timer"].ToString(); //Appconfig "03:00"
    var date = DateTime.Now;

    DateTime scheduled = DateTime.ParseExact(timer, "HH:mm",
                                            CultureInfo.InvariantCulture);

    if (date > scheduled) scheduled = scheduled.AddDays(1);

    var test = scheduled.Subtract(date).TotalMinutes;

    aTimer.Interval = test;

    aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
    aTimer.Enabled = true;
    aTimer.AutoReset = false;

}

上面的代码在启动时第一次运行,然后即使间隔设置为每天凌晨 3:00 运行,它也不会再次运行。

更新: 效果很好。我想知道如果我将计时器设置为每 1 秒运行一次,它是否有可能与每个事件重叠。在开始新的事件之前是否等待事件结束?

标签: c#windowsservicebackgroundscheduling

解决方案


AutoReset 应该为 true,以便多次引发事件。你为什么把它设置为假?

请参阅https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer.autoreset?view=net-5

但更好的是使用windows scheduler。如果重新启动或重新启动/停止服务,您的代码将无济于事。


推荐阅读