安排 Windows 服务在每天凌晨 3:00 运行

时间:2021-04-17 15:19:21

标签: c# windows service background scheduling

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 秒运行一次,它是否有可能与每个事件重叠。是否要等到活动结束后再开始新活动?

1 个答案:

答案 0 :(得分:1)

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

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

但更好的是使用 Windows 调度程序。在重新启动或重新启动/停止服务的情况下,您的代码将无济于事。

相关问题