Quartz.Net 调度框架配置介绍
在平时的工作中,估计大多数都做过轮询调度的任务,比如定时轮询数据库同步,定时邮件通知等等。大家通过windows计划任务,windows服务等都实现过此类任务,甚至实现过自己的配置定制化的框架。那今天就来介绍个开源的调度框架Quartz.Net(主要介绍配置的实现,因为有朋友问过此类问题)。调度的实现代码很简单,在源码中有大量Demo,这里就略过了。
Quartz.Net当前最新版本 Quartz.NET 2.0 beta 1 Released
一 基于文件配置
先看一下简单的实现代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Quartz;
using Quartz.Impl;
using Common.Logging; namespace Demo
{
class Program
{
static void Main(string[] args)
{ // First we must get a reference to a scheduler
ISchedulerFactory sf = new StdSchedulerFactory();
IScheduler sched = sf.GetScheduler(); sched.Start();
sched.Shutdown(true); }
}
}
代码很简单,配置文件中的quartz基础配置,以及job,trigger信息是如何加载的?这个过程是发生 IScheduler sched = sf.GetScheduler();过程,主要体现在源码这一段
public void Initialize()
{
// short-circuit if already initialized
if (cfg != null)
{
return;
}
if (initException != null)
{
throw initException;
} NameValueCollection props = (NameValueCollection) ConfigurationManager.GetSection("quartz"); string requestedFile = Environment.GetEnvironmentVariable(PropertiesFile);
string propFileName = requestedFile != null && requestedFile.Trim().Length > ? requestedFile : "~/quartz.config"; // check for specials
propFileName = FileUtil.ResolveFile(propFileName); if (props == null && File.Exists(propFileName))
{
// file system
try
{
PropertiesParser pp = PropertiesParser.ReadFromFileResource(propFileName);
props = pp.UnderlyingProperties;
Log.Info(string.Format("Quartz.NET properties loaded from configuration file '{0}'", propFileName));
}
catch (Exception ex)
{
Log.Error("Could not load properties for Quartz from file {0}: {1}".FormatInvariant(propFileName, ex.Message), ex);
} }
if (props == null)
{
// read from assembly
try
{
PropertiesParser pp = PropertiesParser.ReadFromEmbeddedAssemblyResource("Quartz.quartz.config");
props = pp.UnderlyingProperties;
Log.Info("Default Quartz.NET properties loaded from embedded resource file");
}
catch (Exception ex)
{
Log.Error("Could not load default properties for Quartz from Quartz assembly: {0}".FormatInvariant(ex.Message), ex);
}
}
if (props == null)
{
throw new SchedulerConfigException(
@"Could not find <quartz> configuration section from your application config or load default configuration from assembly.
Please add configuration to your application config file to correctly initialize Quartz.");
}
Initialize(OverrideWithSysProps(props));
}
通过上面代码分析,初始化首先会检查系统config中是否有<quartz> configuration section节点 (config指的app.config,web.config),如果系统config有quartz节点,则直接加载此处的配置信息。如果系统config没有quartz的基础配置信息,则会继续查找是否有quartz.config/Quartz.quartz.config 这两个配置文件的存在,如果有则加载配置信息,如果没有则扔出初始化配置异常。
而jobs.xml(调度的任务和触发器plugin节点配置文件)
app.config/web.config 中plugin配置
<quartz>
<add key="quartz.scheduler.instanceName" value="ExampleDefaultQuartzScheduler"/>
<add key="quartz.threadPool.type" value="Quartz.Simpl.SimpleThreadPool, Quartz"/>
<add key="quartz.threadPool.threadCount" value=""/>
<add key="quartz.threadPool.threadPriority" value=""/>
<add key="quartz.jobStore.misfireThreshold" value=""/>
<add key="quartz.jobStore.type" value="Quartz.Simpl.RAMJobStore, Quartz"/>
<!--******************************Plugin配置********************************************* -->
<add key="quartz.plugin.xml.type" value="Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz" />
<add key="quartz.plugin.xml.fileNames" value="quartz_jobs.xml"/>
</quartz>
quartz.config 中plugin配置指向(quartz.plugin.xml.type / quartz.plugin.xml.fileNames)
# You can configure your scheduler in either <quartz> configuration section
# or in quartz properties file
# Configuration section has precedence quartz.scheduler.instanceName = ServerScheduler # configure thread pool info
quartz.threadPool.type = Quartz.Simpl.SimpleThreadPool, Quartz
quartz.threadPool.threadCount =
quartz.threadPool.threadPriority = Normal #--------------------------------*************plugin配置------------------------------------
# job initialization plugin handles our xml reading, without it defaults are used
quartz.plugin.xml.type = Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz
quartz.plugin.xml.fileNames = ~/quartz_jobs.xml # export this server to remoting context
quartz.scheduler.exporter.type = Quartz.Simpl.RemotingSchedulerExporter, Quartz
quartz.scheduler.exporter.port =
quartz.scheduler.exporter.bindName = QuartzScheduler
quartz.scheduler.exporter.channelType = tcp
quartz.scheduler.exporter.channelName = httpQuartz
二 基于代码的方式
这种情况直接通过代码实现的,官方DEMO很多都是如此,我们举个例子
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using Quartz;
using Quartz.Impl;
using System.Threading;
using Common.Logging; namespace Demo
{
class Program
{
static void Main(string[] args)
{
ILog log = LogManager.GetLogger(typeof(Demo.HelloJob)); log.Info("------- Initializing ----------------------"); // First we must get a reference to a scheduler
ISchedulerFactory sf = new StdSchedulerFactory();
IScheduler sched = sf.GetScheduler(); log.Info("------- Initialization Complete -----------"); //---------------------------------------代码添加job和trigger
// computer a time that is on the next round minute
DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow); log.Info("------- Scheduling Job -------------------"); // define the job and tie it to our HelloJob class
IJobDetail job = JobBuilder.Create<HelloJob>()
.WithIdentity("job1", "group1")
.Build(); // Trigger the job to run on the next round minute
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("trigger1", "group1")
.StartAt(runTime)
.Build(); // Tell quartz to schedule the job using our trigger
sched.ScheduleJob(job, trigger);
log.Info(string.Format("{0} will run at: {1}", job.Key, runTime.ToString("r"))); // Start up the scheduler (nothing can actually run until the
// scheduler has been started)
sched.Start();
log.Info("------- Started Scheduler -----------------"); // wait long enough so that the scheduler as an opportunity to
// run the job!
log.Info("------- Waiting 65 seconds... -------------"); // wait 65 seconds to show jobs
Thread.Sleep(TimeSpan.FromSeconds()); // shut down the scheduler
log.Info("------- Shutting Down ---------------------");
sched.Shutdown(true);
log.Info("------- Shutdown Complete -----------------");
}
}
}
其实代码方式已经实现了和配置文件混搭的方式了。但是这种对方式是通过配置关联加载job与trigger配置,我们还有第三种方式,自己加载job与trigger配置文件。
三 手动加载配置文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Quartz;
using Quartz.Xml;
using Quartz.Impl;
using Quartz.Simpl;
using System.Threading;
using Common.Logging;
using System.IO; namespace Demo
{
class Program
{
static void Main(string[] args)
{
XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper());
ISchedulerFactory sf = new StdSchedulerFactory();
IScheduler scheduler = sf.GetScheduler(); Stream s = new StreamReader("~/quartz.xml").BaseStream;
processor.ProcessStream(s, null);
processor.ScheduleJobs(scheduler); scheduler.Start();
scheduler.Shutdown(); }
}
}
亦或者这样
using System.Text;
using Quartz;
using Quartz.Xml;
using Quartz.Impl;
using Quartz.Simpl;
using System.Threading;
using Common.Logging;
using System.IO; namespace Demo
{
class Program
{
static void Main(string[] args)
{
XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper());
ISchedulerFactory sf = new StdSchedulerFactory();
IScheduler scheduler = sf.GetScheduler(); processor.ProcessFileAndScheduleJobs("~/quartz.xml",scheduler); scheduler.Start();
scheduler.Shutdown(); }
}
}
目前根据源码分析大致就这几种配置方式,很灵活可以任意组合。 关于quartz的使用源码很详细,并且园子量有大量的学习文章。
记住quartz的配置读取方式首先app.config/web.config ---->quartz.config/Quartz.quartz.config ---->quartz_jobs.xml .
通过代码方式我们可以改变quartz_jobs.xml 的指向即自己新命名的xml文件
(默认的quartz_jobs.xml是在XMLSchedulingDataProcessor.QuartzXmlFileName = "quartz_jobs.xml"被指定的)
方式一,通过quartz节点/quartz.config指向指定的jobs.xml。
方式二,通过XMLSchedulingDataProcessor 加载指定的jobs.xml
Quartz.Net 调度框架配置介绍的更多相关文章
- Java任务调度框架之分布式调度框架XXL-Job介绍
Java任务调度框架之分布式调度框架XXL-Job介绍及快速入门 调度器使用场景: Java开发中经常会使用到定时任务:比如每月1号凌晨生成上个月的账单.比如每天凌晨1点对上一天的数据进行对账操作 ...
- Quartz定时调度框架
Quartz定时调度框架CronTrigger时间配置格式说明 CronTrigger时间格式配置说明 CronTrigger配置格式: 格式: [秒] [分] [小时] [日] [月] [周] [年 ...
- Quartz基础调度框架-第二篇服务
很多应用场景Quartz运行于Windows服务 Conf 在这个基本结构里 是用来存放配置 和上一篇 控制台运行的一样的结构 jobs.xml 的配置清单 <!-- 任务配置--> & ...
- Quartz基础调度框架-第一篇控制台
Quartz基础调度框架 Quartz核心的概念:scheduler任务调度.Job任务.Trigger触发器.JobDetail任务细节 结构 Conf 在这个基本结构里 是用来存放配置 publi ...
- Spring Quartz定时调度任务配置
applicationContext-quartz.xml定时调度任务启动代码: <?xml version="1.0" encoding="UTF-8" ...
- k8s调度器介绍(调度框架版本)
从一个pod的创建开始 由kubectl解析创建pod的yaml,发送创建pod请求到APIServer. APIServer首先做权限认证,然后检查信息并把数据存储到ETCD里,创建deployme ...
- Quartz.net 开源job调度框架(一)
Quartz.NET是一个开源的作业调度框架,非常适合在平时的工作中,定时轮询数据库同步,定时邮件通知,定时处理数据等. Quartz.NET允许开发人员根据时间间隔(或天)来调度作业.它实现了作业和 ...
- Quartz.net(调度框架) 使用Mysql作为存储
最近公司的做的项目中涉及到配置任务地址然后按照配置去目标地址提取相关的数据,所以今天上午在Internet上查看有关定时任务(调度任务)的相关信息,筛选半天然后查找到Quartz.net. Quart ...
- 山寨版Quartz.Net任务统一调度框架
TaskScheduler 在日常工作中,大家都会经常遇到Win服务,在我工作的这些年中一直在使用Quartz.Net这个任务统一调度框架,也非常好用,配置简单,但是如果多个项目组的多个服务部署到一台 ...
随机推荐
- In_interrupt( ) 和In_irq( )【转】
转自:http://blog.csdn.net/do2jiang/article/details/5486888 in_interrupt() 是判断当前进程是否处于中断上下文,这个中断上下文包括底半 ...
- (转)java线程安全问题之静态变量、实例变量、局部变量
java多线程编程中,存在很多线程安全问题,至于什么是线程安全呢,给出一个通俗易懂的概念还是蛮难的,如同<java并发编程实践>中所说: 写道 给线程安全下定义比较困难.存在很多种定义,如 ...
- Oracle 单行函数
一.什么是函数 任何东西,只要它能接收输入,对输入进行加工并产生输出,它就可以被称为函数. 二.单行函数简介 单行函数只对表中的一行数据进行操作,并且对每一行数据只产生一个输出结果.单行函数可以接受一 ...
- 对于改善 MySQL 数据装载操作有效率的方法是怎样
多时候关心的是优化SELECT 查询,因为它们是最常用的查询,而且确定怎样优化它们并不总是直截了当.相对来说,将数据装入数据库是直截了当的.然而,也存在可用来改善数据装载操作效率的策略,其基本原理如下 ...
- Ecshop后台订单列表增加”商品名”检索字段
近期ecshop网站做活动,统计商品订单量的时候没有按商品名搜索的选项,只能手动查询.这样效率很低下,而且容易出错. 现在为列表增加一个简单的“按商品名搜索”表单项.效果如下图 涉及到2个文件,分别是 ...
- [Unity3D][Vuforia][ios]使用vuforia的unity3d库在ios中摄像头只显示黑色,不显示摄像头,NO CAMERA的解决方案
注:我使用的是Vuforia 4.0SDK Unity3D5.0版本,跑的ios系统为8.1 我在Vuforia官方讨论贴子中看到这其实是新手都会遇到的问题 贴子地址: https://develop ...
- 复利计算--4.0 单元测试之JAVA版-软件工程
复利计算--4.0 单元测试-软件工程 前言:由于本人之前做的是C语言版的复利计算,所以为了更好地学习单元测试,于是将C语言版的复利计算修改为JAVA版的. 一.主要的功能需求细分: 1.本金为100 ...
- centos6.5版本改系统语言成中文简体
root:locale -a 查看系统支持的语言,如果看到这个zh_CN.utf8(这是中文简体)说明系统支持此语言 root:vim /etc/sysconfig/i18n(编辑语言的配置文件) 输 ...
- json-lib date对象转json ,加入自定义日期格式处理
import net.sf.json.JSONObject; import net.sf.json.JsonConfig; import net.sf.json.processors.JsonValu ...
- datagrid 重写属性
$.fn.panel.defaults.loadMsg = '数据加载中请稍后--'; //设置默认的分页参数 if ($.fn.datagrid) { $.fn.datagrid.defaults. ...