我有一个用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(); } }
查看Quartz.NET.您可以在Windows服务中使用它.它允许您根据配置的计划运行作业,甚至支持简单的"cron作业"语法.我用它取得了很大的成功.
以下是其用法的简单示例:
// Instantiate the Quartz.NET scheduler var schedulerFactory = new StdSchedulerFactory(); var scheduler = schedulerFactory.GetScheduler(); // Instantiate the JobDetail object passing in the type of your // custom job class. Your class merely needs to implement a simple // interface with a single method called "Execute". var job = new JobDetail("job1", "group1", typeof(MyJobClass)); // Instantiate a trigger using the basic cron syntax. // This tells it to run at 1AM every Monday - Friday. var trigger = new CronTrigger( "trigger1", "group1", "job1", "group1", "0 0 1 ? * MON-FRI"); // Add the job to the scheduler scheduler.AddJob(job, true); scheduler.ScheduleJob(trigger);
日常任务?听起来它应该只是一个计划任务(控制面板) - 这里不需要服务.
它必须是实际的服务吗?您可以在Windows控制面板中使用内置的计划任务吗?