我怎么可能会安排一个C#Windows服务来执行日常任务? [英] How might I schedule a C# Windows Service to perform a task daily?

查看:120
本文介绍了我怎么可能会安排一个C#Windows服务来执行日常任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写在C#(.NET 1.1)服务,并希望它执行在午夜进行一些清理行动,每一个夜晚。我必须保持包含在服务中的所有code,有啥做到这一点最简单的方法?使用 Thread.sleep代码()键,滚来滚去检查的时候?

I have a service written in C# (.NET 1.1) and want it to perform some cleanup actions at midnight every night. I have to keep all code contained within the service, so what's the easiest way to accomplish this? Use of Thread.Sleep() and checking for the time rolling over?

推荐答案

我不会用Thread.sleep()方法。要么使用计划任务(如其他人所说的),或者设置你的服务,定期触发内部计时器(每10分钟为例),并检查是否上次运行以来更改日期:

I wouldn't use Thread.Sleep(). Either use a scheduled task (as others have mentioned), or set up a timer inside your service, which fires periodically (every 10 minutes for example) and check if the date changed since the last run:

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服务来执行日常任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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