Quartz.Net系列(十六):通过Plugins模式使用Xml方式配置Job和Trigger和自定义LogPrivider
1.简单介绍
Quarz.Net中采用插件式来实现配置文件配置,通过XMLSchedulingDataProcessor类进行Xml数据处理
默认配置文件命名:quart_jobs.xml
public const string QuartzXmlFileName = "quartz_jobs.xml";
2.创建配置
首先安装扩展程序:Liquid XML Objects(基于XML的xsd文件创建数据模型)
新建quartz_jobs.xml文件,选择XML=>Schemas
Add
quartz_jobs.xml
<?xml version="1.0" encoding="utf-8" ?>
<job-scheduling-data xmlns="http://quartznet.sourceforge.net/JobSchedulingData">
<processing-directives>
<overwrite-existing-data>true</overwrite-existing-data>
</processing-directives> <schedule>
<job>
<name>myJob</name>
<group>aaron</group>
<description>这是Xml定义的Job</description>
<job-type>Quartz_Demo.MyJob,Quartz_Demo</job-type>
<durable>true</durable>
<recover>true</recover>
<job-data-map>
<entry>
<key>myKey</key>
<value>myValue</value>
</entry>
</job-data-map>
</job>
<trigger>
<simple>
<name>myTrigger</name>
<description>这是Xml定义的Trigger</description>
<job-name>myJob</job-name>
<job-group>aaron</job-group>
<repeat-count>-1</repeat-count>
<repeat-interval>1000</repeat-interval>
</simple>
</trigger>
</schedule>
</job-scheduling-data>
安装Quartz.Plugins包
编写代码
var assemblyName = typeof(Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin).AssemblyQualifiedName; var scheduler= await SchedulerBuilder.Create().UseXmlSchedulingConfiguration((options)=>{
options.SetProperty("quartz.plugin.xml.fileNames", "quartz_jobs.xml");
options.SetProperty("quartz.plugin.xml.scanInterval", "");
options.SetProperty("quartz.threadPool.threadCount", "");
}).Build(); //System.Collections.Specialized.NameValueCollection collection = new System.Collections.Specialized.NameValueCollection(); //collection.Add("quartz.plugin.xml.type", assemblyName); //collection.Add("quartz.plugin.xml.fileNames","quartz_jobs.xml"); //collection.Add("quartz.plugin.xml.scanInterval", "10"); //var factory = new StdSchedulerFactory(collection); //var scheduler = await factory.GetScheduler(); LogProvider.SetCurrentLogProvider(new ConsoleLogProvider()); await scheduler.Start(); var metaData=await scheduler.GetMetaData(); Console.WriteLine(metaData.ThreadPoolSize);
自定义LogPrivider
public class ConsoleLogProvider : ILogProvider
{
public Logger GetLogger(string name)
{
Logger loger = (logLevel, messageFunc, exception, formatParameters) =>
{
if (logLevel >= LogLevel.Debug && messageFunc != null)
{
Console.WriteLine("[" + DateTime.Now.ToLongTimeString() + "] [" + logLevel + "] " + messageFunc(), formatParameters);
}
return true;
}; return loger;
} public IDisposable OpenMappedContext(string key, object value, bool destructure = false)
{
return null;
} public IDisposable OpenNestedContext(string message)
{
return null;
}
}
运行图
源码解析
foreach (jobdetailType jobDetailType in jobNodes)
{
string jobName = jobDetailType.name.TrimEmptyToNull();
string jobGroup = jobDetailType.group.TrimEmptyToNull();
string jobDescription = jobDetailType.description.TrimEmptyToNull();
string jobTypeName = jobDetailType.jobtype.TrimEmptyToNull();
bool jobDurability = jobDetailType.durable;
bool jobRecoveryRequested = jobDetailType.recover; Type jobType = TypeLoadHelper.LoadType(jobTypeName); IJobDetail jobDetail = JobBuilder.Create(jobType)
.WithIdentity(jobName, jobGroup)
.WithDescription(jobDescription)
.StoreDurably(jobDurability)
.RequestRecovery(jobRecoveryRequested)
.Build(); if (jobDetailType.jobdatamap != null && jobDetailType.jobdatamap.entry != null)
{
foreach (entryType entry in jobDetailType.jobdatamap.entry)
{
string key = entry.key.TrimEmptyToNull();
string value = entry.value.TrimEmptyToNull();
jobDetail.JobDataMap.Add(key, value);
}
} if (Log.IsDebugEnabled())
{
Log.Debug("Parsed job definition: " + jobDetail);
} AddJobToSchedule(jobDetail);
} //
// Extract Trigger definitions...
// List<triggerType> triggerEntries = new List<triggerType>();
if (data.schedule != null)
{
foreach (var schedule in data.schedule)
{
if (schedule != null && schedule.trigger != null)
{
triggerEntries.AddRange(schedule.trigger);
}
}
} Log.Debug("Found " + triggerEntries.Count + " trigger definitions."); foreach (triggerType triggerNode in triggerEntries)
{
string triggerName = triggerNode.Item.name.TrimEmptyToNull();
string triggerGroup = triggerNode.Item.group.TrimEmptyToNull();
string triggerDescription = triggerNode.Item.description.TrimEmptyToNull();
string triggerCalendarRef = triggerNode.Item.calendarname.TrimEmptyToNull();
string triggerJobName = triggerNode.Item.jobname.TrimEmptyToNull();
string triggerJobGroup = triggerNode.Item.jobgroup.TrimEmptyToNull(); int triggerPriority = TriggerConstants.DefaultPriority;
if (!triggerNode.Item.priority.IsNullOrWhiteSpace())
{
triggerPriority = Convert.ToInt32(triggerNode.Item.priority);
} DateTimeOffset triggerStartTime = SystemTime.UtcNow();
if (triggerNode.Item.Item != null)
{
if (triggerNode.Item.Item is DateTime time)
{
triggerStartTime = new DateTimeOffset(time);
}
else
{
triggerStartTime = triggerStartTime.AddSeconds(Convert.ToInt32(triggerNode.Item.Item));
}
} DateTime? triggerEndTime = triggerNode.Item.endtimeSpecified ? triggerNode.Item.endtime : (DateTime?) null; IScheduleBuilder sched; if (triggerNode.Item is simpleTriggerType simpleTrigger)
{
string repeatCountString = simpleTrigger.repeatcount.TrimEmptyToNull();
string repeatIntervalString = simpleTrigger.repeatinterval.TrimEmptyToNull(); int repeatCount = ParseSimpleTriggerRepeatCount(repeatCountString);
TimeSpan repeatInterval = repeatIntervalString == null ? TimeSpan.Zero : TimeSpan.FromMilliseconds(Convert.ToInt64(repeatIntervalString)); sched = SimpleScheduleBuilder.Create()
.WithInterval(repeatInterval)
.WithRepeatCount(repeatCount); if (!simpleTrigger.misfireinstruction.IsNullOrWhiteSpace())
{
((SimpleScheduleBuilder) sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(simpleTrigger.misfireinstruction));
}
}
else if (triggerNode.Item is cronTriggerType)
{
cronTriggerType cronTrigger = (cronTriggerType) triggerNode.Item;
string cronExpression = cronTrigger.cronexpression.TrimEmptyToNull();
string timezoneString = cronTrigger.timezone.TrimEmptyToNull(); TimeZoneInfo tz = timezoneString != null ? TimeZoneUtil.FindTimeZoneById(timezoneString) : null;
sched = CronScheduleBuilder.CronSchedule(cronExpression)
.InTimeZone(tz); if (!cronTrigger.misfireinstruction.IsNullOrWhiteSpace())
{
((CronScheduleBuilder) sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(cronTrigger.misfireinstruction));
}
}
else if (triggerNode.Item is calendarIntervalTriggerType)
{
calendarIntervalTriggerType calendarIntervalTrigger = (calendarIntervalTriggerType) triggerNode.Item;
string repeatIntervalString = calendarIntervalTrigger.repeatinterval.TrimEmptyToNull(); IntervalUnit intervalUnit = ParseDateIntervalTriggerIntervalUnit(calendarIntervalTrigger.repeatintervalunit.TrimEmptyToNull());
int repeatInterval = repeatIntervalString == null ? : Convert.ToInt32(repeatIntervalString); sched = CalendarIntervalScheduleBuilder.Create()
.WithInterval(repeatInterval, intervalUnit); if (!calendarIntervalTrigger.misfireinstruction.IsNullOrWhiteSpace())
{
((CalendarIntervalScheduleBuilder) sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(calendarIntervalTrigger.misfireinstruction));
}
}
else
{
throw new SchedulerConfigException("Unknown trigger type in XML configuration");
} IMutableTrigger trigger = (IMutableTrigger) TriggerBuilder.Create()
.WithIdentity(triggerName, triggerGroup)
.WithDescription(triggerDescription)
.ForJob(triggerJobName, triggerJobGroup)
.StartAt(triggerStartTime)
.EndAt(triggerEndTime)
.WithPriority(triggerPriority)
.ModifiedByCalendar(triggerCalendarRef)
.WithSchedule(sched)
.Build(); if (triggerNode.Item.jobdatamap != null && triggerNode.Item.jobdatamap.entry != null)
{
foreach (entryType entry in triggerNode.Item.jobdatamap.entry)
{
string key = entry.key.TrimEmptyToNull();
string value = entry.value.TrimEmptyToNull();
trigger.JobDataMap.Add(key, value);
}
} if (Log.IsDebugEnabled())
{
Log.Debug("Parsed trigger definition: " + trigger);
} AddTriggerToSchedule(trigger);
}
Quartz.Net系列(十六):通过Plugins模式使用Xml方式配置Job和Trigger和自定义LogPrivider的更多相关文章
- S3C2416裸机开发系列十六_sd卡驱动实现
S3C2416裸机开发系列十六 sd卡驱动实现 象棋小子 1048272975 SD卡(Secure Digital Memory Card)具有体积小.容量大.传输数据快.可插拔.安全性好等长 ...
- MVVM模式解析和在WPF中的实现(六) 用依赖注入的方式配置ViewModel并注册消息
MVVM模式解析和在WPF中的实现(六) 用依赖注入的方式配置ViewModel并注册消息 系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二 ...
- Spring系列之aAOP AOP是什么?+xml方式实现aop+注解方式实现aop
Spring系列之aop aop是什么?+xml方式实现aop+注解方式实现aop 什么是AOP? AOP为Aspect Oriented Programming 的缩写,意识为面向切面的编程,是通过 ...
- 学习ASP.NET Core Razor 编程系列十六——排序
学习ASP.NET Core Razor 编程系列目录 学习ASP.NET Core Razor 编程系列一 学习ASP.NET Core Razor 编程系列二——添加一个实体 学习ASP.NET ...
- 为什么不让用join?《死磕MySQL系列 十六》
大家好,我是咔咔 不期速成,日拱一卒 在平时开发工作中join的使用频率是非常高的,很多SQL优化博文也让把子查询改为join从而提升性能,但部分公司的DBA又不让用,那么使用join到底有什么问题呢 ...
- Spring Boot2 系列教程(十六)定时任务的两种实现方式
在 Spring + SpringMVC 环境中,一般来说,要实现定时任务,我们有两中方案,一种是使用 Spring 自带的定时任务处理器 @Scheduled 注解,另一种就是使用第三方框架 Qua ...
- 十六、Spring Boot 部署与服务配置
spring Boot 其默认是集成web容器的,启动方式由像普通Java程序一样,main函数入口启动.其内置Tomcat容器或Jetty容器,具体由配置来决定(默认Tomcat).当然你也可以将项 ...
- SpringBoot填坑系列---XML方式配置数据库
本次只是简单的运用SpringBoot搭建框架,对其原理并不做深入的探究 1.POM文件 <?xml version="1.0" encoding="UTF-8&q ...
- webpack4 系列教程(十六):开发模式和生产模式·实战
好文章 https://www.jianshu.com/p/f2d30d02b719
随机推荐
- windows RN 环境搭建(实测心得)
首先安装官网的装好依赖 这里特别敲掉的是 jdk 必须要1.8的才行: 装了node 就不要 py了. 官网 其次安装 android studio 开发工具 把对应的都装好: 这里的 ...
- Spring Boot]SpringBoot四大神器之Actuator
论文转载自博客: https://blog.csdn.net/Dreamhai/article/details/81077903 https://bigjar.github.io/2018/08/19 ...
- 6、struct2使用servlet的api函数
方法一: Struts2的Action访问Servlet API 可以通过实现装配接口没,完成对Servlet API的访问 * ServletRequestAware取得HttpServletReq ...
- Redis持久化机制,优缺点,如何选择合适方式
一.什么是Redis持久化? 持久化就是把内存的数据写到磁盘中去,防止服务宕机了内存数据丢失. 二.Redis 的持久化机制是什么?各自的优缺点? Redis 提供两种持久化机制 RDB(默认) 和 ...
- 为什么 char c = 'A';c += 32; 结果输出的是 'a'?
首先 char 类型的数据只要参与运行会先转换为 int 类型数值(在 ASCII 编码表中 'A' 对应十进制的 65),那么 'A' 转换为 int 为 65,65 + 32 = 97,+= 包含 ...
- 计算机网络之tcp四次挥手
TCP的四次挥手(Four-Way Wavehand)1.前言对于"三次握手"我们耳熟能详,因为其相对的简单.但是,我们却不常听见“四次挥手”,就算听过也未必能详细地说明白它的具体 ...
- ubuntu18.04安装nodejs最新版、指定版 12.x 14.x
今天准备在 ubuntu 服务器里面安装 nodejs 版本,ubuntu 18.04 仓库 nodejs 默认是 8.x 版本. 1. 通过 apt 安装 nodejs 在 Ubuntu 18.04 ...
- js事件入门(1)
1.事件相关概念 1.1 什么是事件? 事件是用户在访问页面时执行的操作,也就是用户访问页面时的行为.当浏览器探测到一个事件时,比如鼠标点击或者按键.它可以触发与这个事件相关的JavaScript对象 ...
- 序列推荐(transformer)
目录 Attention演进(RNN&LSTM&GRU&Seq2Seq + Attention机制) LSTM GRU Seq2Seq + Attention机制 Attent ...
- python之浅谈编程语言
一.编程语言的分类 机器语言(低级语言) 可以直接和硬件交互,用0和1和计算机沟通 优点:执行效率高(因为可以直接和计算机沟通) 缺点:开发效率低(都是用0和1进行编码) 汇编语言 同样可以直接和硬件 ...