Quartz.Net 官方教程 Tutorial 3/3
Schedule
-
相关属性设置
-
扩展属性方式
var host = Host.CreateDefaultBuilder() .ConfigureServices(services => { services.AddQuartz(opt => { // 主键 opt.SchedulerId = ""; // 调度名称 opt.SchedulerName = ""; // 最大并发(一次运行Job的最大数) opt.MaxBatchSize = ""; // 可中断作业 opt.InterruptJobsOnShutdown = true; // 关机时中断作业可等待 opt.InterruptJobsOnShutdownWithWait = true; // 批量设置触发器的执行的提前时间 q.BatchTriggerAcquisitionFireAheadTimeWindow = TimeSpan.Zero; }); }) .Build();
-
手动实例化
var scheduler = ScheduleBuilder().Create() .WithMisfireThreshold(TimeSpan.FromDays(1)) .WithId("") .WithName("") .WithMaxBatchSize(2) .WithInterruptJobsOnShutdown(true) .WithInterruptJobsOnShutdownWithWait(true) // 提前1分钟进行批量执行 .WithBatchTriggerAcquisitionFireAheadTimeWindow(TimeSpan.FromMilliseconds(1)) .Build();
-
-
StdSchedulerFactory
默认使用的调度工厂,相关配置文件存储在本地进行加载。
-
DirectSchedulerFactory
不建议使用,除非:对于Quartz.NET很熟悉并且所有配置项都能通过代码进行配置
-
Loggin
-
从3.1开始,可以通过配置Microsoft.Extensions.Logging.Abstractions来代替 LibLog library
-
实例化配置
// obtain your logger factory, for example from IServiceProvider ILoggerFactory loggerFactory = ...; // Quartz 3.1 Quartz.LogContext.SetCurrentLogProvider(loggerFactory); // Quartz 3.2 onwards Quartz.Logging.LogContext.SetCurrentLogProvider(loggerFactory);
-
使用Microsoft DI 集成进行配置
services.AddQuartz(q => { // this automatically registers the Microsoft Logging });
-
Clustering
-
集群配置,仅适用于JobStore设置为JobStoreTX时
-
如果IJobDetail中RequestRecovery设置为true,负载均衡和作业故障转移会被启用
-
通过配置 quartz.jobStore.clustered=true来启用集群模式,集群中每个实例都有相同的副本
- 每个节点必须有一个唯一的instanceId(quartz.scheduler.instanceId)
注:
1.单独的机器不要运行集群,
2.同一个数据库不能在集群启动后在链接一个非集群的实例
3.如果某个节点CPU到达了100%时,请优化它,不然会存在丢失作业的风险
配置资源
默认情况下,StdSchedulerFactory会从当前工作目录中加载quartz.config
文件,如果失败,则会加载quartz.dll中的配置文件。非默认情况下可通过修改quartz.properties进行文件设置
可使用以下四种方式进行配置信息
-
通过Initialize或StdSchedulerFactory方法修改
// 创建Collection System.Collections.Specialized.NameValueCollection collection = new System.Collections.Specialized.NameValueCollection(); // 新增key和value collection.Add("quartz.threadPool.ThreadCount","20"); // 实例化调度工厂 var factory= new StdSchedulerFactory(collection); // 也可以通过factory.Initialize(NameValueCollection)来初始化 // Initialize必须在GetScheduler方法之前 factory.Initialize(collection); // 获得调度实例 var scheduler= await factory.GetScheduler();
-
App.config配置
.net Framework生效
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="quartz" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089"/> </configSections> <quartz> <add key="quartz.threadPool.ThreadCount" value="11"/> </quartz> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" /> </startup> </configuration>
-
quartz.config配置
-
Enviroment(环境变量配置)
// 设置环境变量 Environment.SetEnvironmentVariable("quartz.threadPool.ThreadCount","50"); System.Collections.Specialized.NameValueCollection collection = new System.Collections.Specialized.NameValueCollection(); var factory = new StdSchedulerFactory(); var scheduler= await factory.GetScheduler();
主要配置项
配置项名称 | Required | 类型 | 默认值 | 说明 |
---|---|---|---|---|
quartz.scheduler.instanceName | no | string | 'QuartzScheduler' | 客户端/集群:区分调度器 |
quartz.scheduler.instanceId | no | string | 'NON_CLUSTERED' | 唯一键 AUTO:自动生成 SYS_PROP:系统属性生成 |
quartz.scheduler.instanceIdGenerator.type | no | string | Quartz.Simpl.SimpleInstanceIdGenerator, Quartz | instanceId设置为AUTO时生效 |
quartz.scheduler.threadName | no | string | instanceName + '_QuartzSchedulerThread' | 调度线程名称 |
quartz.scheduler.makeSchedulerThreadDaemon | no | boolean | false | 是否为守护线程 |
quartz.scheduler.idleWaitTime | no | long | 30000 | 空闲时,重新查询触发器的等待时间,不能小于5000ms |
quartz.scheduler.typeLoadHelper.type | no | string | Quartz.Simpl.SimpleTypeLoadHelper | Type.GetType()加载 |
quartz.scheduler.jobFactory.type | no | string | Quartz.Simpl.PropertySettingJobFactory | 工厂的类型名称 |
quartz.context.key.SOME_KEY | no | string | none | 设置“quartz.context.key.MyKey=MyValue” 将执行schedule.context.Put(“MyKey”,“MyValue”) |
quartz.scheduler.batchTriggerAcquisitionMaxCount | no | int | 1 | 集群使用,当前节点最大触发数 |
quartz.scheduler.batchTriggerAcquisitionFireAheadTimeWindow | no | long | 0 | 在计划触发之前可以获取几个触发器,数量越大越不精确触发 |
线程池配置项
Property Name | Required | Type | Default Value | 说明 |
---|---|---|---|---|
quartz.threadPool.type | no | string | Quartz.Simpl.DefaultThreadPool, Quartz | 线程池类型 |
quartz.threadPool.maxConcurrency | no | int | 10 | 最大并发数 |
自定义线程池
/*
系统自带
DedicatedThreadPool 自定义了线程池(声明了专用的线程池)
TaskSchedulingThreadPool 使用TaskScheduler调度任务
ZeroSizeThreadPool 零大小线程池
*/
// MyLibrary为dll名称
// MyLibrary.FooThreadPool 命名空间+类名
quartz.threadPool.type = MyLibrary.FooThreadPool, MyLibrary
// 未给出说明
quartz.threadPool.somePropOfFooThreadPool = someValue
监听配置项
可以由StdSchedulerFactory实例化和配置
// MyListenerType必须有无参构造函数
//触发器注册监听(全局)
// 空间+类型, dll名称
quartz.triggerListener.NAME.type = MyLibrary.MyListenerType, MyLibrary
// 属性名称
quartz.triggerListener.NAME.propName = propValue
// 属性名称
quartz.triggerListener.NAME.prop2Name = prop2Value
// 作业注册监听(全局)
quartz.jobListener.NAME.type = MyLibrary.MyListenerType, MyLibrary
quartz.jobListener.NAME.propName = propValue
quartz.jobListener.NAME.prop2Name = prop2Value
插件配置项
与监听类似,配置一个插件,插件类型必须有无参构造函数
quartz.plugin.NAME.type = MyLibrary.MyPluginType, MyLibrary
quartz.plugin.NAME.propName = propValue
quartz.plugin.NAME.prop2Name = prop2Value
-
日志记录触发器历史插件
// 引用插件,需要有Quartz.Plugins.dll文件 quartz.plugin.triggHistory.type = Quartz.Plugin.History.LoggingTriggerHistoryPlugin, Quartz.Plugins // 启动信息 quartz.plugin.triggHistory.triggerFiredMessage = Trigger {1}.{0} fired job {6}.{5} at: {4:HH:mm:ss MM/dd/yyyy} // 完成信息 quartz.plugin.triggHistory.triggerCompleteMessage = Trigger {1}.{0} completed firing job {6}.{5} at {4:HH:mm:ss MM/dd/yyyy} with resulting trigger instruction code: {9}
-
XML调度数据处理器插件
作业初始化插件从XML文件中读取一组作业和触发器,并在初始化期间将它们添加到调度程序中;它还可以删除现有数据。
quartz.plugin.jobInitializer.type = Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz.Plugins // 读取的文件路径 quartz.plugin.jobInitializer.fileNames = data/my_job_data.xml // 未找到报错 quartz.plugin.jobInitializer.failOnFileNotFound = true
-
关机钩子插件
捕获CLR终止的事件,并在调度程序上调用shutdown
quartz.plugin.shutdownhook.type = Quartz.Plugin.Management.ShutdownHookPlugin, Quartz.Plugins quartz.plugin.shutdownhook.cleanShutdown = true
-
作业中断监视器插件
捕获作业长时间运行(超过配置的最大时间)的事件,并告诉调度程序在启用时“尝试”中断它。插件默认为5分钟后发出信号中断,但默认的defaultMaxRunTime配置为不同的值,配置值以毫秒为单位。
quartz.plugin.jobAutoInterrupt.type = Quartz.Plugin.Interrupt.JobInterruptMonitorPlugin, Quartz.Plugins quartz.plugin.jobAutoInterrupt.defaultMaxRunTime = 3000000
远程服务端客户端
Property Name | Required | Type | Default Value | 说明 |
---|---|---|---|---|
quartz.scheduler.exporter.type | yes | string | Quartz.Simpl.RemotingSchedulerExport,Quartz | 只有这一种 |
quartz.scheduler.exporter.port | yes | int | 端口号 | |
quartz.scheduler.exporter.bindName | no | string | QuartzScheduler | QuartzScheduler为对外暴露的名称 |
quartz.scheduler.exporter.channelType | no | string | 'tcp' | tpc/http tcp性能高 |
quartz.scheduler.exporter.channelName | no | string | 'http' | 对外暴露的通道名称 |
quartz.scheduler.exporter.typeFilterLevel | no | string | 'Full' | Low:低反序列化级别 Full:完整的反序列化类型 |
quartz.scheduler.exporter.rejectRemoteRequests | no | boolean | false | 是否接受远程请求 |
RAMJobStore
- 必须配置项
quartz.jobStore.type = Quartz.Simpl.RAMJobStore, Quartz
Property Name | Required | Type | Default Value | 说明 |
---|---|---|---|---|
quartz.jobStore.misfireThreshold | no | int | 60000 | 触发器执行触发的最小时间间隔 |
JobStoreTx(ADO.NET)
- 必须配置项
quartz.jobStore.type = Quartz.Impl.AdoJobStore.JobStoreTX, Quartz
Property Name | Required | Type | Default Value | 说明 |
---|---|---|---|---|
quartz.jobStore.dbRetryInterval | no | long | 15000 (15 seconds) | 间隔15秒重新连接 |
quartz.jobStore.driverDelegateType | yes | string | null | 参见下文 |
quartz.jobStore.dataSource | yes | string | null | 数据库名称 |
quartz.jobStore.tablePrefix | no | string | "QRTZ_" | 表前缀 |
quartz.jobStore.useProperties | no | boolean | false | true:使用BLOB类型存储 |
quartz.jobStore.misfireThreshold | no | int | 60000 | 触发器执行触发的最小时间间隔-ms |
quartz.jobStore.clustered | no | boolean | false | 是否开启集群 |
quartz.jobStore.clusterCheckinInterval | no | long | 15000 | 检查集群周期 -ms |
quartz.jobStore.maxMisfiresToHandleAtATime | no | int | 20 | 最大处理错误数 |
quartz.jobStore.selectWithLockSQL | no | string | "SELECT * FROM {0}LOCKS WHERE SCHED_NAME = {1} AND LOCK_NAME = ? FOR UPDATE" | “{0}”将替换为上面配置的tablePrefix;“{1}”替换为调度程序的名称。 |
quartz.jobStore.txIsolationLevelSerializable | no | boolean | false | true:设置事务级别 |
quartz.jobStore.acquireTriggersWithinLock | no | boolean | false (or true - see doc below) | 用于锁定作业存储数据的控制 |
quartz.jobStore.lockHandler.type | no | string | null | 默认即可,自定义可参见下文StdRowLockSemaphore |
quartz.jobStore.driverDelegateInitString | no | string | null |
-
quartz.jobStore.driverDelegateType
可选择类型如下:
- Quartz.Impl.AdoJobStore.StdAdoDelegate, Quartz - default when no specific implementation available
- Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz - for Microsoft SQL Server
- Quartz.Impl.AdoJobStore.PostgreSQLDelegate, Quartz
- Quartz.Impl.AdoJobStore.OracleDelegate, Quartz
- Quartz.Impl.AdoJobStore.SQLiteDelegate, Quartz
- Quartz.Impl.AdoJobStore.MySQLDelegate, Quartz
-
quartz.jobStore.lockHandler.type
自定义 StdRowLockSemaphore
// 自定义设置 quartz.jobStore.lockHandler.type = Quartz.Impl.AdoJobStore.StdRowLockSemaphore quartz.jobStore.lockHandler.maxRetry = 7 # Default is 3 quartz.jobStore.lockHandler.retryPeriod = 3000 # Default is 1000 millis
DataSources(ADO.NET JobStores)
Property Name | Required | Type | 说明 |
---|---|---|---|
quartz.dataSource.NAME.provider | yes | string | |
quartz.dataSource.NAME.connectionString | no | string | 连接字符串 |
quartz.dataSource.NAME.connectionStringName | no | string | app.config or appsettings.json定义的连接名称 |
quartz.dataSource.NAME.connectionProvider.type | no | string | 自定义连接提供程序 |
-
quartz.dataSource.NAME.provider
可设置列表如下:
-
SqlServer
- Microsoft SQL Server -
OracleODP
- Oracle's Oracle Driver -
OracleODPManaged
- Oracle's managed driver for Oracle 11 -
MySql
- MySQL Connector/.NET -
SQLite
- SQLite ADO.NET Provider -
SQLite-Microsoft
- Microsoft SQLite ADO.NET Provider -
Firebird
- Firebird ADO.NET Provider -
Npgsql
- PostgreSQL Npgsql该列表与JobStore不同,以此为准。
-
Clustering 集群
官网提供的全量集群配置信息,具体配置项可参见Clustering
#============================================================================
# Configure Main Scheduler Properties
#============================================================================
quartz.scheduler.instanceName = MyClusteredScheduler
quartz.scheduler.instanceId = AUTO
#============================================================================
# Configure ThreadPool
#============================================================================
quartz.threadPool.type = Quartz.Simpl.DefaultThreadPool, Quartz
quartz.threadPool.threadCount = 25
quartz.threadPool.threadPriority = 5
#============================================================================
# Configure JobStore
#============================================================================
quartz.jobStore.misfireThreshold = 60000
quartz.jobStore.type = Quartz.Impl.AdoJobStore.JobStoreTX
quartz.jobStore.driverDelegateType = Quartz.Impl.AdoJobStore.SqlServerDelegate
quartz.jobStore.useProperties = true
quartz.jobStore.dataSource = myDS
quartz.jobStore.tablePrefix = QRTZ_
quartz.jobStore.clustered = true
quartz.jobStore.clusterCheckinInterval = 20000
#============================================================================
# Configure Datasources
#============================================================================
quartz.dataSource.myDS.provider = SqlServer
quartz.dataSource.myDS.connectionString = Server=localhost;Database=quartznet;User Id=quartznet;Password=quartznet;