Quartz+TopShelf实现定时任务

转自

https://www.cnblogs.com/frozenzhang/archive/2016/04/29/5443778.html

 

1.创建控制台程序

 

2.添加引用

添加TopShelf的引用:TopShelf和TopShelf.Quartz

注:因为开发环境不一样,添加的版本会不同,即VS版本过低则无法安装最新的TopShelf

使用Nuget添加引用,默认添加的是最新的版本

  

或用命令行(可选择低版本):

1  Install-Package Topshelf -Version 3.3.0
2 
3  Install-Package Topshelf.Quartz -Version 0.4.0

需要注意的是安装 Topshelf.Quartz 的时候,Quartz已经默认安装,所以不再需要单独安装

此时的代码的引用结构如下:

 

3.创建ServiceRunner.cs类

用于管理代码的启动等操作:

 1     public class ServiceRunner : ServiceControl, ServiceSuspend
 2     {
 3         private readonly IScheduler scheduler;
 4         public ServiceRunner()
 5         {
 6             scheduler = StdSchedulerFactory.GetDefaultScheduler();
 7         }
 8         public bool Start(HostControl hostControl)
 9         {
10             //启动调度器
11             scheduler.Start();
12             //具体任务启动可在配置文件编写
13             string cron1 = ConfigurationManager.AppSettings["cron1"].ToString();
14             if(!string.IsNullOrEmpty(cron1))
15             {
16                 IJobDetail job1 = JobBuilder.Create<TestJob1>().Build();
17                 ITrigger trigger1 = TriggerBuilder.Create().StartNow().WithCronSchedule(cron1).Build();
18                 scheduler.ScheduleJob(job1, trigger1);
19             }
20 
21             return true;
22         }
23         public bool Continue(HostControl hostControl)
24         {
25             scheduler.ResumeAll();
26             return true;
27         }
28 
29         public bool Pause(HostControl hostControl)
30         {
31             scheduler.PauseAll();
32             return true;
33         } 
36 
37         public bool Stop(HostControl hostControl)
38         {
39             scheduler.Shutdown(false);
40             return true;
41         }
42     }

4.修改启动代码 

修改Programs.cs中的代码

 1   HostFactory.Run(x =>
 2    {
 3        x.Service<ServiceRunner>();
 4  
 5        x.RunAsLocalSystem();
 6  
 7        x.SetDescription("Quartz+TopShelf实现Windows服务作业调度的一个示例Demo");
 8        x.SetDisplayName("QuartzTopShelfDemo服务");
 9        x.SetServiceName("QuartzTopShelfDemoService");
10  
11        x.EnablePauseAndContinue();
12    });

5.修改业务代码

1     public class TestJob1 : IJob
2     {
3         public void Execute(IJobExecutionContext context)
4         {
5             Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
6         }
7     }

最终效果如下:

7.代码地址

https://github.com/imstrive/WinService

8.参考

https://www.quartz-scheduler.net/documentation/quartz-3.x/quick-start.html

http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/crontrigger.html

https://blog.csdn.net/mituan1234567/article/details/50953474

http://www.mpustelak.com/2017/01/scheduled-jobs-made-easy-topshelf-quartz-net/

原文地址:https://www.cnblogs.com/imstrive/p/9973265.html