1、创建项目
项目类型控制台应用程序,.Net Framework框架版本 4.7.2
2、引入框架
NuGet\Install-Package Quartz -Version 3.8.0
3、创建Job
自定义Job实现接口IJob,在Execute方法实现定时逻辑,
using Quartz;
using System;
using System.Threading.Tasks;namespace QuartzConsole
{public class MyJob : IJob{public Task Execute(IJobExecutionContext context){return Console.Out.WriteLineAsync($"任务开始执行了:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");}}
}
4、创建调度器实例
使用工厂类StdSchedulerFactory创建调度器实例,
StdSchedulerFactory factory = new StdSchedulerFactory();//创建工厂实例var scheduler = await factory.GetScheduler();//创建调度器await scheduler.Start();//启动调度器
5、创建Job实例
使用Job构建器创建任务实例,
IJobDetail job = JobBuilder.Create<MyJob>().WithIdentity("job1", "group1").Build();
6、创建触发器
使用触发器构建器创建触发器实例,触发器包含简单触发器和正则表达式触发器,比如重复执行多少次这种简单的逻辑,可以使用简单触发器,比如每天21点-23点,每隔2分钟的第5秒开始执行任务,则适合使用正则表达式触发器来构建。
简单触发器:
#region 简单触发器,每隔5秒重复执行ITrigger trigger = TriggerBuilder.Create().WithIdentity("trigger", "group1").WithSimpleSchedule(x=>x.WithInterval(TimeSpan.FromSeconds(5)).RepeatForever()).Build();#endregion
正则表达式触发器:
#region 每天21点-23点,每隔2分钟的第5秒开始执行ITrigger trigger = TriggerBuilder.Create().WithIdentity("trigger", "group1").WithCronSchedule("5 0/2 21-23 * * ?").Build();#endregion
触发器正则表达式生成可以借助工具,参考链接:
Free Online Cron Expression Generator and Describer - FreeFormatter.com
7、将任务和触发器安排到调度器
await scheduler.ScheduleJob(job, trigger);
8、完整代码
using Quartz;
using Quartz.Impl;
using Quartz.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace QuartzConsole
{class Program{async static Task Main(string[] args){StdSchedulerFactory factory = new StdSchedulerFactory();var scheduler = await factory.GetScheduler();await scheduler.Start();IJobDetail job = JobBuilder.Create<MyJob>().WithIdentity("job1", "group1").Build();//#region 每天21点-23点,每隔2分钟的第5秒开始执行//ITrigger trigger = TriggerBuilder.Create()// .WithIdentity("trigger", "group1")// .WithCronSchedule("5 0/2 21-23 * * ?")// .Build();//#endregion//#region 每天21:33执行//ITrigger trigger = TriggerBuilder.Create()// .WithIdentity("trigger", "group1")// .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(21,33))// .Build();//#endregion#region 每周五21:36执行//ITrigger trigger = TriggerBuilder.Create()// .WithIdentity("trigger", "group1")// .WithSchedule(CronScheduleBuilder.WeeklyOnDayAndHourAndMinute(DayOfWeek.Friday,21,36))// .Build();//ITrigger trigger = TriggerBuilder.Create()// .WithIdentity("trigger", "group1")// .WithCronSchedule("0 39 21 ? * FRI")// .Build();#endregion#region 简单触发器,每隔5秒重复执行ITrigger trigger = TriggerBuilder.Create().WithIdentity("trigger", "group1").WithSimpleSchedule(x=>x.WithInterval(TimeSpan.FromSeconds(5)).RepeatForever()).Build();#endregionawait scheduler.ScheduleJob(job, trigger);Console.WriteLine("Press any key to close the application");Console.ReadKey();}}
}
官方学习文档:Cron Triggers | Quartz.NET