如何安排C#Windows服务每天执行任务?
我有一个用C#(.NET
1.1)编写的服务,希望它在每晚的午夜执行一些清理操作。我必须将所有代码包含在服务中,那么最简单的方法是什么?使用Thread.Sleep()时间检查时间吗?
回答:
我不会使用Thread.Sleep()。使用预定任务(如其他人所述),或在服务内部设置计时器,该计时器会定期触发(例如每10分钟触发一次),并检查自上次运行以来日期是否更改:
private Timer _timer;private DateTime _lastRun = DateTime.Now.AddDays(-1);
protected override void OnStart(string[] args)
{
    _timer = new Timer(10 * 60 * 1000); // every 10 minutes
    _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
    _timer.Start();
    //...
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    // ignore the time, just compare the date
    if (_lastRun.Date < DateTime.Now.Date)
    {
        // stop the timer while we are running the cleanup task
        _timer.Stop();
        //
        // do cleanup stuff
        //
        _lastRun = DateTime.Now;
        _timer.Start();
    }
}
以上是 如何安排C#Windows服务每天执行任务? 的全部内容, 来源链接: utcz.com/qa/403379.html








