Quartz.NET是一个开源的作业调度框架。
官网地址:https://www.quartz-scheduler.net/
目前最新版本为3.0.7,需要.NET Framework 4.5.2及更高版本以上。
.NET Framework 4.0及以下可以用版本2.6.2。
本文用的是2.6.2版本,下面为入门例子。
1、创建2个简单任务
Hello1Job.cs
public class Hello1Job : IJob { public void Execute(IJobExecutionContext context) { LogHelper.Info("hello1"); } }
Hello2Job.cs
public class Hello2Job : IJob { public void Execute(IJobExecutionContext context) { LogHelper.Info("hello2"); } }
2、创建任务服务
QuartzService.cs
//引用Quartz、Quartz.Impl; public class QuartzService { //调度器 IScheduler scheduler; public QuartzService() { //调度器工厂 ISchedulerFactory factory = new StdSchedulerFactory(); scheduler = factory.GetScheduler(); } public void Start() { //创建任务 IJobDetail job1 = JobBuilder.Create<Hello1Job>().WithIdentity(new JobKey("job1")).Build(); //创建触发器,配置3秒执行一次 ITrigger trigger1 = TriggerBuilder.Create().WithCronSchedule("0/3 * * * * ?") .Build(); //创建任务 IJobDetail job2 = JobBuilder.Create<Hello2Job>().WithIdentity(new JobKey("job2")).Build(); //创建触发器,配置5秒执行一次 ITrigger trigger2 = TriggerBuilder.Create().WithCronSchedule("0/5 * * * * ?").Build(); //将任务与触发器添加到调度器中,如果需要多个就绑定多个即可 scheduler.ScheduleJob(job1, trigger1); scheduler.ScheduleJob(job2, trigger2); //开始执行 scheduler.Start(); } public void Shutdown() { if (scheduler != null) { scheduler.Shutdown(true); } } }
3、调用
QuartzService quartzJob = new QuartzService(); quartzJob.Start();
运行结果如下:
2019-06-03 09:52:39,667 [DefaultQuartzScheduler_Worker-1] INFO logging - hello1 2019-06-03 09:52:40,000 [DefaultQuartzScheduler_Worker-2] INFO logging - hello2 2019-06-03 09:52:42,000 [DefaultQuartzScheduler_Worker-3] INFO logging - hello1 2019-06-03 09:52:45,000 [DefaultQuartzScheduler_Worker-4] INFO logging - hello1 2019-06-03 09:52:45,000 [DefaultQuartzScheduler_Worker-5] INFO logging - hello2 2019-06-03 09:52:48,000 [DefaultQuartzScheduler_Worker-6] INFO logging - hello1 2019-06-03 09:52:50,000 [DefaultQuartzScheduler_Worker-7] INFO logging - hello2 2019-06-03 09:52:51,000 [DefaultQuartzScheduler_Worker-8] INFO logging - hello1 2019-06-03 09:52:54,000 [DefaultQuartzScheduler_Worker-9] INFO logging - hello1 2019-06-03 09:52:55,000 [DefaultQuartzScheduler_Worker-10] INFO logging - hello2
来源:https://www.cnblogs.com/gdjlc/p/10966289.html