.net6 webapi项目使用quartz做定时任务,之前已经写过文章入门了解了quartz的使用
.net6 webapi项目需要引入如下包(版本号都是3.6.0)
Install-Package Quartz
Install-Package Quartz.Extensions.Hosting
Install-Package Quartz.Extensions.DependencyInjection
然后在Program.cs中加入如下配置代码
//quartz 定时任务
builder.Services.AddQuartz(q =>
{
q.SchedulerId = "FactorySchedule";
q.UseMicrosoftDependencyInjectionJobFactory();//注入
//默认设置
q.UseSimpleTypeLoader();
q.UseInMemoryStore();
q.UseDedicatedThreadPool(tp =>
{
tp.MaxConcurrency = 10;
});
// quickest way to create a job with single trigger is to use ScheduleJob
// (requires version 3.2)
//q.ScheduleJob<TestJob>(trigger => trigger
// .WithIdentity("TestJob")
// .StartAt(DateBuilder.EvenSecondDate(DateTimeOffset.UtcNow.AddSeconds(7)))
// .WithDailyTimeIntervalSchedule(x => x.WithInterval(1, IntervalUnit.Minute))
// .WithDescription("TestJobDescription")
//);
var jobKey = new JobKey("TestJob");
q.AddJob<CaseSummaryJob>(opts => opts.WithIdentity(jobKey));
q.AddTrigger(opts => opts
.ForJob(jobKey)
.WithIdentity("TestJob-trigger")
.WithSimpleSchedule(x => x.WithIntervalInMinutes(3).RepeatForever())
.StartNow()
//This Cron interval can be described as "run every minute" (when second is zero)
//.WithCronSchedule("0 * * ? * *")
);
});
// we can use options pattern to support hooking your own configuration
// because we don't use service registration api,
// we need to manually ensure the job is present in DI
builder.Services.AddTransient<TestJob>();
// Quartz.Extensions.Hosting allows you to fire background service that handles scheduler lifecycle
// when shutting down we want jobs to complete gracefully
builder.Services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true);
参考官方文档:Quartz.NET
其他quartz介绍参考C# quartz.net 定时任务(一)_woflyoycm的博客-CSDN博客_c#定时job