Quartz.Extensions.DependencyInjection 提供与 Microsoft Dependency 依赖注入 的集成
提示
需要 Quartz 3.1 或更高版本。
安装
您需要将 NuGet 包引用添加到使用 Quartz 的项目中。
Install-Package Quartz.Extensions.DependencyInjection
使用
您可以通过在 IServiceCollection 上调用扩展方法 AddQuartz 来添加 Quartz 配置。 配置构建使用强类型 API 包装各种配置属性。 您还可以使用配置部分 Quartz 中的标准 .NET Core appsettings.json 配置属性。
提示
Quartz.Extensions.Hosting 允许您为您的应用程序提供一个后台服务,用于处理启动和停止调度程序。
示例 appsettings.json
{"Logging": {"LogLevel": {"Default": "Information","Microsoft": "Warning","Microsoft.Hosting.Lifetime": "Information"}},"Quartz": {"quartz.scheduler.instanceName": "Quartz ASP.NET Core Sample Scheduler"}}
DI 感知工作工厂
Quartz 带有两个内置的作业工厂替代方案,可以通过调用 UseMicrosoftDependencyInjectionJobFactory 或 UseMicrosoftDependencyInjectionScopedJobFactory(已弃用)进行配置。
提示
从 Quartz.NET 3.3.2 开始,默认作业工厂生成的所有作业都是作用域作业,您不应再使用
UseMicrosoftDependencyInjectionScopedJobFactory。
作业实例构建
默认情况下,Quartz 将尝试从容器中解析作业的类型,如果没有显式注册,Quartz 将使用 ActivatorUtilities 构造作业并通过构造函数注入它的依赖项。 Job 应该只有一个公共构造函数。
持久性作业存储
每次您的应用程序启动并评估计划时,将根据数据库检查计划配置并相应更新。
警告
使用持久作业存储时,请确保为调度定义作业和触发器名称,以便存在性检查针对数据库中已有的数据正确工作。
使用 API 配置触发器和作业而没有明确的作业标识配置将导致作业和触发器在每次评估配置时生成不同的名称。
对于持久性作业存储,最好始终至少声明作业和触发器名称。 为它们省略组将为每次调用生成相同的默认组值。
示例 Startup.ConfigureServices 配置
public void ConfigureServices(IServiceCollection services){// 来自 appsettings.json 的基本配置services.Configure<QuartzOptions>(Configuration.GetSection("Quartz"));// 如果您使用的是持久作业存储,您可能需要更改一些选项services.Configure<QuartzOptions>(options =>{options.Scheduling.IgnoreDuplicates = true; // 默认值:falseoptions.Scheduling.OverWriteExistingData = true; // 默认值:true});services.AddQuartz(q =>{// 当集群的一部分或您想以其他方式识别多个调度程序时很方便q.SchedulerId = "Scheduler-Core";// 我们从 appsettings.json 中获取它,// 只是表明它是可能的 q.SchedulerName = "Quartz ASP.NET Core Sample Scheduler";// 从 3.3.2 开始,这也可以毫无问题地注入作用域服务(如 EF DbContext)q.UseMicrosoftDependencyInjectionJobFactory();// 或用于范围服务支持,例如 EF Core DbContext// q.UseMicrosoftDependencyInjectionScopedJobFactory();// 这些是默认值q.UseSimpleTypeLoader();q.UseInMemoryStore();q.UseDefaultThreadPool(tp =>{tp.MaxConcurrency = 10;});// 使用单个触发器创建作业的最快方法是使用 ScheduleJob// (需要 3.2 版)q.ScheduleJob<ExampleJob>(trigger => trigger.WithIdentity("Combined Configuration Trigger").StartAt(DateBuilder.EvenSecondDate(DateTimeOffset.UtcNow.AddSeconds(7))).WithDailyTimeIntervalSchedule(x => x.WithInterval(10, IntervalUnit.Second)).WithDescription("my awesome trigger configured for a job with single call"));// 您还可以使用代码配置单个作业和触发器,这允许您将多个触发器与同一个作业相关联// (例如,如果您希望每个触发器有不同的作业数据映射)q.AddJob<ExampleJob>(j => j.StoreDurably() // 如果没有关联触发器,我们需要持久存储.WithDescription("my awesome job"));// 这是触发器的已知工作var jobKey = new JobKey("awesome job", "awesome group");q.AddJob<ExampleJob>(jobKey, j => j.WithDescription("my awesome job"));q.AddTrigger(t => t.WithIdentity("Simple Trigger").ForJob(jobKey).StartNow().WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromSeconds(10)).RepeatForever()).WithDescription("my awesome simple trigger"));q.AddTrigger(t => t.WithIdentity("Cron Trigger").ForJob(jobKey).StartAt(DateBuilder.EvenSecondDate(DateTimeOffset.UtcNow.AddSeconds(3))).WithCronSchedule("0/3 * * * * ?").WithDescription("my awesome cron trigger"));// 您也可以添加日历(需要 3.2 版)const string calendarName = "myHolidayCalendar";q.AddCalendar<HolidayCalendar>(name: calendarName,replace: true,updateTriggers: true,x => x.AddExcludedDate(new DateTime(2020, 5, 15)));q.AddTrigger(t => t.WithIdentity("Daily Trigger").ForJob(jobKey).StartAt(DateBuilder.EvenSecondDate(DateTimeOffset.UtcNow.AddSeconds(5))).WithDailyTimeIntervalSchedule(x => x.WithInterval(10, IntervalUnit.Second)).WithDescription("my awesome daily time interval trigger").ModifiedByCalendar(calendarName));// 还可以添加 XML 配置并轮询它以进行更改q.UseXmlSchedulingConfiguration(x =>{x.Files = new[] { "~/quartz_jobs.config" };x.ScanInterval = TimeSpan.FromSeconds(2);x.FailOnFileNotFound = true;x.FailOnSchedulingError = true;});// 使用可以处理 Windows/Linux 差异的转换器转换时区q.UseTimeZoneConverter();// 自动中断长时间运行的作业q.UseJobAutoInterrupt(options =>{// 这是默认的options.DefaultMaxRunTime = TimeSpan.FromMinutes(5);});q.ScheduleJob<SlowJob>(triggerConfigurator => triggerConfigurator.WithIdentity("slowJobTrigger").StartNow().WithSimpleSchedule(x => x.WithIntervalInSeconds(5).RepeatForever()),jobConfigurator => jobConfigurator.WithIdentity("slowJob").UsingJobData(JobInterruptMonitorPlugin.JobDataMapKeyAutoInterruptable, true)// 此作业只允许五秒钟,覆盖默认配置.UsingJobData(JobInterruptMonitorPlugin.JobDataMapKeyMaxRunTime, TimeSpan.FromSeconds(5).TotalMilliseconds.ToString(CultureInfo.InvariantCulture)));// 添加一些监听器q.AddSchedulerListener<SampleSchedulerListener>();q.AddJobListener<SampleJobListener>(GroupMatcher<JobKey>.GroupEquals(jobKey.Group));q.AddTriggerListener<SampleTriggerListener>();// 以 JSON 序列化器为例的持久作业存储示例/*q.UsePersistentStore(s =>{s.UseProperties = true;s.RetryInterval = TimeSpan.FromSeconds(15);s.UseSqlServer(sqlServer =>{sqlServer.ConnectionString = "some connection string";// 这是默认的sqlServer.TablePrefix = "QRTZ_";});s.UseJsonSerializer();s.UseClustering(c =>{c.CheckinMisfireThreshold = TimeSpan.FromSeconds(20);c.CheckinInterval = TimeSpan.FromSeconds(10);});});*/});// 我们可以使用选项模式来支持挂接您自己的配置,// 因为我们不使用服务注册 api,// 我们需要手动确保作业存在于 DI 中services.AddTransient<ExampleJob>();services.Configure<SampleOptions>(Configuration.GetSection("Sample"));services.AddOptions<QuartzOptions>().Configure<IOptions<SampleOptions>>((options, dep) =>{if (!string.IsNullOrWhiteSpace(dep.Value.CronSchedule)){var jobKey = new JobKey("options-custom-job", "custom");options.AddJob<ExampleJob>(j => j.WithIdentity(jobKey));options.AddTrigger(trigger => trigger.WithIdentity("options-custom-trigger", "custom").ForJob(jobKey).WithCronSchedule(dep.Value.CronSchedule));}});// Quartz.Extensions.Hosting 允许您触发处理调度程序生命周期的后台服务services.AddQuartzHostedService(options =>{// 关闭时,我们希望作业优雅地完成options.WaitForJobsToComplete = true;});}
