在平时的工作中,估计大多数都做过轮询调度的任务,比如定时轮询数据库同步,定时邮件通知等等。大家通过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 调度框架配置介绍的更多相关文章

  1. Java任务调度框架之分布式调度框架XXL-Job介绍

    ​ Java任务调度框架之分布式调度框架XXL-Job介绍及快速入门 调度器使用场景: Java开发中经常会使用到定时任务:比如每月1号凌晨生成上个月的账单.比如每天凌晨1点对上一天的数据进行对账操作 ...

  2. Quartz定时调度框架

    Quartz定时调度框架CronTrigger时间配置格式说明 CronTrigger时间格式配置说明 CronTrigger配置格式: 格式: [秒] [分] [小时] [日] [月] [周] [年 ...

  3. Quartz基础调度框架-第二篇服务

    很多应用场景Quartz运行于Windows服务 Conf 在这个基本结构里 是用来存放配置  和上一篇 控制台运行的一样的结构 jobs.xml 的配置清单 <!-- 任务配置--> & ...

  4. Quartz基础调度框架-第一篇控制台

    Quartz基础调度框架 Quartz核心的概念:scheduler任务调度.Job任务.Trigger触发器.JobDetail任务细节 结构 Conf 在这个基本结构里 是用来存放配置 publi ...

  5. Spring Quartz定时调度任务配置

    applicationContext-quartz.xml定时调度任务启动代码: <?xml version="1.0" encoding="UTF-8" ...

  6. k8s调度器介绍(调度框架版本)

    从一个pod的创建开始 由kubectl解析创建pod的yaml,发送创建pod请求到APIServer. APIServer首先做权限认证,然后检查信息并把数据存储到ETCD里,创建deployme ...

  7. Quartz.net 开源job调度框架(一)

    Quartz.NET是一个开源的作业调度框架,非常适合在平时的工作中,定时轮询数据库同步,定时邮件通知,定时处理数据等. Quartz.NET允许开发人员根据时间间隔(或天)来调度作业.它实现了作业和 ...

  8. Quartz.net(调度框架) 使用Mysql作为存储

    最近公司的做的项目中涉及到配置任务地址然后按照配置去目标地址提取相关的数据,所以今天上午在Internet上查看有关定时任务(调度任务)的相关信息,筛选半天然后查找到Quartz.net. Quart ...

  9. 山寨版Quartz.Net任务统一调度框架

    TaskScheduler 在日常工作中,大家都会经常遇到Win服务,在我工作的这些年中一直在使用Quartz.Net这个任务统一调度框架,也非常好用,配置简单,但是如果多个项目组的多个服务部署到一台 ...

随机推荐

  1. CDN流量放大攻击思路

    首先,为了对CDN进行攻击,我们必须清楚CDN的工作原理,这里我们再来简单介绍一下CDN的工作模型. CDN的全称是Content Delivery Network(内容分发网络),通过在网络各处的加 ...

  2. Install Sogou IM 2.0 in Ubuntu14.04+/Xfce

    Ubuntu14.04+ 安装搜狗输入法 搜狗输入法是一款非常友好的输入法产品,从Ubuntu14.04开始对Linux支持,不过只是Debian系的,是Ubuntu优麒麟组引入的.优麒麟是针对国人设 ...

  3. hobby

    如果把战争的原则凝缩为一个词,那就是集中. 人生有三把钥匙, 接受. 改变. 离开.不能接受,那就改变,不能改变,那就离开. 少问别人为什么,多问自己凭什么. 太平自古将军定,不许将军见太平

  4. JavaEE基础(十三)

    1.常见对象(StringBuffer类的概述) A:StringBuffer类概述 通过JDK提供的API,查看StringBuffer类的说明 线程安全的可变字符序列 B:StringBuffer ...

  5. 使用Symfony 2在三小时内开发一个寻人平台

    简介 Symfony2是一个基于PHP语言的Web开发框架,有着开发速度快.性能高等特点.但Symfony2的学习曲线也比 较陡峭,没有经验的初学者往往需要一些练习才能掌握其特性. 本文通过一个快速开 ...

  6. ACM第二站————归并排序

    转载请注明出处,谢谢!http://www.cnblogs.com/Asimple/p/5459664.html 归并排序————二分的思想 以中间的数为基准,每次排序都将比其小[升序排](大[降序排 ...

  7. python: indentationerror: unexpected indent

    以后遇到了IndentationError: unexpected indent你就要知道python编译器是在告诉你“Hi,老兄,你的文件里格式不对了,可能是tab和空格没对齐的问题,你需要检查下t ...

  8. 【转】MYSQL入门学习之一:基本操作

    转载地址:http://www.2cto.com/database/201212/173868.html 1.登录数据库    www.2cto.com       命令:mysql -u usern ...

  9. Android网络连接之HttpURLConnection和HttpClient

    1.概念   HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源.在 JDK 的 java.net 包中 ...

  10. 20151124001 关闭C#主窗体弹出是否关闭对话框

    关闭C#主窗体弹出是否关闭对话框 private void Frm_Main_FormClosing(object sender, FormClosingEventArgs e)        {   ...