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 ServerOracleODP- Oracle's Oracle DriverOracleODPManaged- Oracle's managed driver for Oracle 11MySql- MySQL Connector/.NETSQLite- SQLite ADO.NET ProviderSQLite-Microsoft- Microsoft SQLite ADO.NET ProviderFirebird- Firebird ADO.NET ProviderNpgsql- 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;
Quartz.Net 官方教程 Tutorial 3/3的更多相关文章
- Quartz.net官方开发指南系列篇
Quartz.NET是一个开源的作业调度框架,是OpenSymphony 的 Quartz API的.NET移植,它用C#写成,可用于winform和asp.net应用中.它提供了巨大的灵活性而不牺牲 ...
- Unity性能优化(3)-官方教程Optimizing garbage collection in Unity games翻译
本文是Unity官方教程,性能优化系列的第三篇<Optimizing garbage collection in Unity games>的翻译. 相关文章: Unity性能优化(1)-官 ...
- Unity性能优化(4)-官方教程Optimizing graphics rendering in Unity games翻译
本文是Unity官方教程,性能优化系列的第四篇<Optimizing graphics rendering in Unity games>的翻译. 相关文章: Unity性能优化(1)-官 ...
- Unity性能优化(2)-官方教程Diagnosing performance problems using the Profiler window翻译
本文是Unity官方教程,性能优化系列的第二篇<Diagnosing performance problems using the Profiler window>的简单翻译. 相关文章: ...
- [爬虫] 学Scrapy,顺便把它的官方教程给爬下来
想学爬虫主要是因为算法和数据是密切相关的,有数据之后可以玩更多有意思的事情,数据量大可以挖掘挖掘到更多的信息. 之前只会通过python中的request库来下载网页内容,再用BeautifulSou ...
- Note | PyTorch官方教程学习笔记
目录 1. 快速入门PYTORCH 1.1. 什么是PyTorch 1.1.1. 基础概念 1.1.2. 与NumPy之间的桥梁 1.2. Autograd: Automatic Differenti ...
- Unity性能优化(1)-官方教程The Profiler window翻译
本文是Unity官方教程,性能优化系列的第一篇<The Profiler window>的简单翻译. 相关文章: Unity性能优化(1)-官方教程The Profiler window翻 ...
- jeecg表单页面控件权限设置(请先看官方教程,如果能看懂就不用看这里了)
只是把看了官方教程后,觉得不清楚地方补充说明一下: 1. 2. 3. 4.用"jeecgDemoController.do?addorupdate"这个路径测试,不出意外现在应该可 ...
- [转]Google Guava官方教程(中文版)
Google Guava官方教程(中文版) http://ifeve.com/google-guava/
- Google Guava官方教程(中文版)
Google Guava官方教程(中文版) 原文链接 译文链接 译者: 沈义扬,罗立树,何一昕,武祖 校对:方腾飞 引言 Guava工程包含了若干被Google的 Java项目广泛依赖 的核心库, ...
随机推荐
- ubuntu下Mysql安装与root密码重置
一.安装 1.首先更新本地存储库索引,执行sudo apt update 2.从APT存储库安装MySQL,执行sudo apt install MySQL-server,在安装过程中,可能会出现[Y ...
- JavaScript 默认参数、动态参数、剩余参数
默认参数: <script> function selet(num, max) { console.log(num + max); } selet(1, 5); </script&g ...
- Day16自定义异常
package com.exception.demo02;//自定义的异常类public class MyException extends Exception{ //传递数字>10抛出异常 p ...
- python 的time、datetime模块
python 时间模块 import datetime res = datetime.datetime.now() print(res) # 2022-08-07 16:47:07.120459 ...
- C#和Open eVision Studio图像库联合编程-读取图像
OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Image Files (*.t ...
- perl中 use strict会出现“requires explicit package name”错误
转载 perl中use strict的用法 如果你使用 use strict 的话,它会强迫你用 my 声明变量,否则将会报上述错误.
- 12 张图看懂 CPU 缓存一致性与 MESI 协议,真的一致吗?
本文已收录到 GitHub · AndroidFamily,有 Android 进阶知识体系,欢迎 Star.技术和职场问题,请关注公众号 [彭旭锐] 进 Android 面试交流群. 前言 大家好 ...
- Training: MySQL I
原题链接:http://www.wechall.net/challenge/training/mysql/auth_bypass1/index.php 题目告诉我们这是一个经典的mysql注入挑战,我 ...
- 初探Java安全之JavaAgent
About Java Agent Java Agent的出现 在JDK1.5版本开始,Java增加了Instrumentation(Java Agent API)和JVMTI(JVM Tool Int ...
- C++ 动态规划:一维动态规划,背包问题,区间动态规划
C++ 动态规划 动态规划的定义 动态规划(Dynamic Programming,DP)是运筹学的一个分支,是求解决策过程最优化的过程.动态规划是一种在数学.管理科学.计算机科学.经济学和生物信息学 ...