1、基本设置根据官方例子整理,作为笔记备忘,当前使用.netcore3.1引入的是quartz.aspnetcore 3.2.4版,在startup中进行配置;
public void ConfigureServices(IServiceCollection services)
{
services.AddQuartzServer(options => { options.WaitForJobsToComplete = true; });
services.AddQuartz(q =>
{
q.SchedulerId = "Scheduler-Core";
q.SchedulerName = "WebApi Quartz Demo";
q.UseMicrosoftDependencyInjectionJobFactory(options =>
{
options.CreateScope = false;
}
);
q.UseSimpleTypeLoader();
q.UseInMemoryStore();
q.UseDedicatedThreadPool(tp => { tp.MaxConcurrency = 10; });
}
}
2、此处记录四种添加job和trigger的方式
- 方式一,使用ScheduleJob快速构建
q.ScheduleJob
(trigger => { trigger.WithIdentity("SingleTrigger").StartNow() .WithSimpleSchedule( action => { action.WithIntervalInSeconds(10).WithRepeatCount(3); }).WithDescription("此任务只拥有单一的trigger"); }); - 方式二,使用AddJob和AddTrigger添加,可以同一个job添加多个trigger
var jobKey = new JobKey("apiDemoJob", "apiDemoJobGroup"); q.AddJob(options => { options.WithIdentity(jobKey).WithDescription("asp.netApi 样例"); }); q.AddTrigger(t => { t.WithIdentity("apiDemoTrigger").ForJob(jobKey).StartNow().WithCronSchedule("0 0/2 * * * ?") .WithDescription("asp.netApi Trigger"); }); - 方式三,通过config配置job和trigger,需引用Quartz.plugins3.2.4
q.UseXmlSchedulingConfiguration(x => { x.Files = new[] { "~/quartz_jobs.config" }; x.ScanInterval = TimeSpan.FromMinutes(1); x.FailOnFileNotFound = true; x.FailOnSchedulingError = true; }); //需要注入job 获取GitHub还没发布的版本测试不需要注入 services.AddTransient(); q.UseMicrosoftDependencyInjectionJobFactory(options => { //此处不设置会有报错,不过任务也能正常执行,github上最新的已移除此属性 options.AllowDefaultConstructor = true; options.CreateScope = false; } ); true XML Job XML Job Group Job configured via XML QuartzWebApi.SampleJob,QuartzWebApi true false key0 value0 key1 value1 key2 value2 XML Trigger SimpleTriggerDescription XML Job XML Job Group 1982-06-28T18:15:00.0Z 2040-05-04T18:13:51.0Z SmartPolicy 2 30000 - 方法四,通过QuartzOptions配置
//需要注入job services.AddTransient(); services.Configure (Configuration.GetSection("Sample")); services.AddOptions ().Configure >((options, dep) => { if (!string.IsNullOrEmpty(dep.Value.CronSchedule)) { var jobKey = new JobKey("optionsCustomJob", "customGroup"); options.AddJob (j => j.WithIdentity(jobKey)); options.AddTrigger(trigger => { trigger.WithIdentity("optionsTrigger", "customGroup").ForJob(jobKey).WithCronSchedule(dep.Value.CronSchedule); }); } }); //"Sample": { // "CronSchedule": "0/25 * * * * ?" //} 配置好之后直接运行就可以了,不需要其它额外设定,真的好方便,部署到IIS中还是要注意资源回收的问题。
- Github:Quartz.Net源码



