Quartz_将持久化配置写在appsettings.json中
准备工作详见:
Quartz.Net_持久化-CSDN博客
持久化配置:
"Quartz": {
"quartz.scheduler.instanceName": "MyScheduler",
"quartz.jobStore.type": "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz",
"quartz.jobStore.dataSource": "ABC",
"quartz.jobStore.driverDelegateType": "Quartz.Impl.AdoJobStore.MySQLDelegate, Quartz",
"quartz.jobStore.useProperties": "true",
"quartz.jobStore.tablePrefix": "QRTZ_",
"quartz.dataSource.ABC.connectionString": "server=localhost;Database=quartz;user id=root;password=123456;SslMode=none;allowPublicKeyRetrieval=true;",
"quartz.dataSource.ABC.provider": "MySql",
"quartz.serializer.type": "json"
}
此处仅作示例,依据实际情况进行修改
注:需要说明的是,详细配置不可写成对象的形式,必需以XXX.YYY.ZZZ的形式书写
Programs.cs
说明详见注释
// 将配置绑定至QuartzOptions(他处需要QuartzOptions时)
// builder.Services.Configure<QuartzOptions>(builder.Configuration.GetSection("Quartz"));
// Quartz配置
builder.Services.AddQuartz(q =>
{
// 该函数在可能在未来被移除(高版本中默认使用微软的依赖注入)
//q.UseMicrosoftDependencyInjectionJobFactory();
q.UsePersistentStore(options =>
{
// 将配置绑定至options
builder.Configuration.GetSection("Quartz").Bind(options);
});
// 可在此处添加Job和Trigger(未调用StoreDurably()也会被持久化)
var jobKey = new JobKey("Job");
q.AddJob<MyJob>(ops => ops.WithIdentity(jobKey));
q.AddTrigger(ops => ops
.ForJob(jobKey)
.WithIdentity("Trigger")
.WithSimpleSchedule(x => x
.WithIntervalInHours(720)
.RepeatForever()
)
);
});
// Quartz的Host配置(与ASP.NET Core项目同生命周期)
builder.Services.AddQuartzHostedService(options =>
{
options.WaitForJobsToComplete = true;
});
关于Host的补充说明
如此也可创建Host,但在ASP.NET中无需如此(存在 var app = builder.Build() 与 app.Run())
var host = CreateHostBuilder(args).Build();
host.Run();
static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((context, services) =>
{
// 从 appsettings.json 中加载 Quartz 配置
services.Configure<QuartzOptions>(context.Configuration.GetSection("Quartz"));
// 添加 Quartz 调度器服务
services.AddQuartz(q =>
{
q.UseMicrosoftDependencyInjectionJobFactory();
//从配置文件加载 Quartz 配置
q.UsePersistentStore(options =>
{
context.Configuration.GetSection("Quartz").Bind(options);
});
var jobKey = new JobKey("Job");
q.AddJob<MyJob>(ops => ops.WithIdentity(jobKey));
q.AddTrigger(ops => ops
.ForJob(jobKey)
.WithDescription("Trigger")
.WithSimpleSchedule(x => x
.WithIntervalInHours(720)
.RepeatForever()
)
);
});
// 添加 Quartz Hosted Service
services.AddQuartzHostedService(options =>
{
options.WaitForJobsToComplete = true;
});
});