Quartz.NET 项目地址 http://quartznet.sourceforge.net/
源码下载地址:Quartz.Net.2.0
- 首先创建Quartz.Net.2.0解决方案,添加 Windows服务 项目,添加安装程序,修改服务运行账户类型为LocalSystem(默认为User)
- 添加C5.dll、Common.Logging.dll、Common.Logging.Log4Net.dll、log4net.dll、Quartz.dll引用
C5.dll 一个C#和其他CLI语言的泛型集合类。.Net2.0及以上才可以使用。简介地址:http://www.itu.dk/research/c5/
Common.Logging.dll 通用日志接口
Common.Logging.Log4Net.dll 提供log4net对通用日志接口(Common.Logging)的实现
log4net.dll 小白都知道不解释 - 添加quartz.config文件 Quartz.Net的app.config配置文件,quartz.config并设置编译时生成到输出目录为始终复制
- Windows服务文件上右键查看代码,编写Quartz服务启动代码,重写OnStart、OnStop、OnPause、OnContinue方法,分别对应IScheduler的Start、Shutdown、PauseAll、ResumeAll方法,详见代码
QuartzService.cs using System.ServiceProcess; using Common.Logging; using Quartz.Impl; namespace Quartz.Net.Service { public partial class QuartzService : ServiceBase { private readonly ILog logger; private IScheduler scheduler; public QuartzService() { InitializeComponent(); logger = LogManager.GetLogger(GetType()); ISchedulerFactory schedulerFactory = new StdSchedulerFactory(); scheduler = schedulerFactory.GetScheduler(); } protected override void OnStart(string[] args) { scheduler.Start(); logger.Info("Quartz服务成功启动"); } protected override void OnStop() { scheduler.Shutdown(); logger.Info("Quartz服务成功终止"); } protected override void OnPause() { scheduler.PauseAll(); } protected override void OnContinue() { scheduler.ResumeAll(); } } }
如下图:
至此Quarzt.Net 的Windows服务已成功创建,接下创建实现了IJob接口Quartz任务
- 添加Quartz.Net.Demo类库项目
- 添加Common.Logging.dll、log4net.dll、Quartz.dll的引用(实际项目中Common.Logging.dll和log4net.dll任意引用一个即可,此处为演示需要)
- 添加DemoJob1.cs,实现IJob接口,日志记录使用Common.Logging接口
DemoJob1.cs using System; namespace Quartz.Net.Demo { /// <summary> /// 实现IJob接口 /// </summary> public class DemoJob1 : IJob { //使用Common.Logging.dll日志接口实现日志记录 private static readonly Common.Logging.ILog logger = Common.Logging.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #region IJob 成员 public void Execute(IJobExecutionContext context) { try { logger.Info("DemoJob1 任务开始运行"); for (int i = 0; i < 10; i++) { logger.InfoFormat("DemoJob1 正在运行{0}", i); } logger.Info("DemoJob1任务运行结束"); } catch (Exception ex) { logger.Error("DemoJob2 运行异常", ex); } } #endregion } }
4.添加DemoJob2.cs,实现IJob接口,日志记录使用log4net
DemoJob2.cs using System; namespace Quartz.Net.Demo { /// <summary> /// 实现IJob接口 /// </summary> public class DemoJob2 : IJob { //使用log4net.dll日志接口实现日志记录 private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #region IJob 成员 public void Execute(IJobExecutionContext context) { try { logger.Info("DemoJob2 任务开始运行"); for (int i = 0; i < 10; i++) { logger.InfoFormat("DemoJob2 正在运行{0}", i); } logger.Info("DemoJob2任务运行结束"); } catch (Exception ex) { logger.Error("DemoJob2 运行异常", ex); } } #endregion } }
如下图:
5.添加quartz_jobs.xml(配置调度任务),需要设置始终复制
quartz_jobs.xml <?xml version="1.0" encoding="UTF-8"?> <!-- This file contains job definitions in schema version 2.0 format --> <job-scheduling-data xmlns="http://quartznet.sourceforge.net/JobSchedulingData" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"> <processing-directives> <overwrite-existing-data>true</overwrite-existing-data> </processing-directives> <schedule> <!--定义示例任务1 Job--> <job> <name>DemoJob1</name> <group>DeomJobGroup</group> <description>Quartz.Net示例任务1</description> <job-type>Quartz.Net.Demo.DemoJob1,Quartz.Net.Demo</job-type> <durable>true</durable> <recover>false</recover> </job> <!--定义示例任务2 Job--> <job> <name>DemoJob2</name> <group>DeomJobGroup</group> <description>Quartz.Net示例任务2</description> <job-type>Quartz.Net.Demo.DemoJob2,Quartz.Net.Demo</job-type> <durable>true</durable> <recover>false</recover> </job> <!--定义示例任务1 触发器 每30秒执行一次DemoJob1任务--> <trigger> <cron> <name>DemoJob1Trigger</name> <group>DeomJobTriggerGroup</group> <job-name>DemoJob1</job-name> <job-group>DeomJobGroup</job-group> <cron-expression>0/30 * * * * ?</cron-expression> </cron> </trigger> <!--定义示例任务2 触发器 每分钟执行一次DemoJob2任务--> <trigger> <cron> <name>DemoJob2Trigger1</name> <group>DeomJobTriggerGroup</group> <job-name>DemoJob2</job-name> <job-group>DeomJobGroup</job-group> <cron-expression>0 * * * * ?</cron-expression> </cron> </trigger> <!--定义示例任务2 触发器 每天凌晨01:00执行一次DemoJob2任务--> <trigger> <cron> <name>DemoJob2Trigger2</name> <group>DeomJobTriggerGroup</group> <job-name>DemoJob2</job-name> <job-group>DeomJobGroup</job-group> <cron-expression>0 0 1 * * ?</cron-expression> </cron> </trigger> </schedule> </job-scheduling-data>
简单触发的图例:
任务配置调度文件节点注释:
job 任务,其实就是1.x版本中的<job-detail>,这个节点是用来定义每个具体的任务的,多个任务请创建多个job节点即可
- name(必填) 任务名称,同一个group中多个job的name不能相同,若未设置group则所有未设置group的job为同一个分组,如:<name>sampleJob</name>
- group(选填) 任务所属分组,用于标识任务所属分组,如:<group>sampleGroup</group>
- description(选填) 任务描述,用于描述任务具体内容,如:<description>Sample job for Quartz Server</description>
- job-type(必填) 任务类型,任务的具体类型及所属程序集,格式:实现了IJob接口的包含完整命名空间的类名,程序集名称,如:<job-type>Quartz.Server.SampleJob, Quartz.Server</job-type>
- durable(选填) 具体作用不知,官方示例中默认为true,如:<durable>true</durable>
- recover(选填) 具体作用不知,官方示例中默认为false,如:<recover>false</recover>
trigger 任务触发器,用于定义使用何种方式出发任务(job),同一个job可以定义多个trigger ,多个trigger 各自独立的执行调度,每个trigger 中必须且只能定义一种触发器类型(calendar-interval、simple、cron)
calendar-interval 一种触发器类型,使用较少,此处略过
simple 简单任务的触发器,可以调度用于重复执行的任务
- name(必填) 触发器名称,同一个分组中的名称必须不同
- group(选填) 触发器组
- description(选填) 触发器描述
- job-name(必填) 要调度的任务名称,该job-name必须和对应job节点中的name完全相同
- job-group(选填) 调度任务(job)所属分组,该值必须和job中的group完全相同
- start-time(选填) 任务开始执行时间utc时间,北京时间需要+08:00,如:<start-time>2012-04-01T08:00:00+08:00</start-time>表示北京时间2012年4月1日上午8:00开始执行,注意服务启动或重启时都会检测此属性,若没有设置此属性或者start-time设置的时间比当前时间较早,则服务启动后会立即执行一次调度,若设置的时间比当前时间晚,服务会等到设置时间相同后才会第一次执行任务,一般若无特殊需要请不要设置此属性
- repeat-count(必填) 任务执行次数,如:<repeat-count>-1</repeat-count>表示无限次执行,<repeat-count>10</repeat-count>表示执行10次
- repeat-interval(必填) 任务触发间隔(毫秒),如:<repeat-interval>10000</repeat-interval> 每10秒执行一次
cron复杂任务触发器--使用cron表达式定制任务调度(强烈推荐)
- name(必填) 触发器名称,同一个分组中的名称必须不同
- group(选填) 触发器组
- description(选填) 触发器描述
- job-name(必填) 要调度的任务名称,该job-name必须和对应job节点中的name完全相同
- job-group(选填) 调度任务(job)所属分组,该值必须和job中的group完全相同
- start-time(选填) 任务开始执行时间utc时间,北京时间需要+08:00,如:<start-time>2012-04-01T08:00:00+08:00</start-time>表示北京时间2012年4月1日上午8:00开始执行,注意服务启动或重启时都会检测此属性,若没有设置此属性,服务会根据cron-expression的设置执行任务调度;若start-time设置的时间比当前时间较早,则服务启动后会忽略掉cron-expression设置,立即执行一次调度,之后再根据cron-expression执行任务调度;若设置的时间比当前时间晚,则服务会在到达设置时间相同后才会应用cron-expression,根据规则执行任务调度,一般若无特殊需要请不要设置此属性
- cron-expression(必填) cron表达式,如:<cron-expression>0/10 * * * * ?</cron-expression>每10秒执行一次
6. 修改app.config,配置Common.logging、log4net
app.config <?xml version="1.0"?> <configuration> <configSections> <section name="quartz" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089"/> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> <sectionGroup name="common"> <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging"/> </sectionGroup> </configSections> <common> <logging> <factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4net"> <arg key="configType" value="INLINE"/> </factoryAdapter> </logging> </common> <log4net> <appender name="InfoFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="log/" /> <appendToFile value="true" /> <param name="DatePattern" value="yyyyMMdd".txt"" /> <rollingStyle value="Date" /> <maxSizeRollBackups value="100" /> <maximumFileSize value="1024KB" /> <staticLogFileName value="false" /> <Encoding value="UTF-8" /> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="INFO" /> <param name="LevelMax" value="INFO" /> </filter> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date %-5level %logger - %message%newline" /> </layout> </appender> <appender name="ErrorFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="log/error.txt" /> <appendToFile value="true" /> <rollingStyle value="Size" /> <maxSizeRollBackups value="100" /> <maximumFileSize value="10240KB" /> <staticLogFileName value="true" /> <Encoding value="UTF-8" /> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="WARN" /> <param name="LevelMax" value="FATAL" /> </filter> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date %-5level %logger - %message%newline" /> </layout> </appender> <root> <level value="INFO" /> <appender-ref ref="InfoFileAppender" /> <appender-ref ref="ErrorFileAppender" /> </root> </log4net> <!-- We use quartz.config for this server, you can always use configuration section if you want to. Configuration section has precedence here. --> <!-- <quartz > </quartz> --> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> </startup> </configuration>
Quartz.Net.Service和Quartz.Net.Demo均创建完毕后,进行编译然后把我们创建的Quartz服务添加到系统的服务中去
- 把编译好的如下文件拷贝到D:QuartzService
- 控制台下执行如下命令:sc create QuartzService binpath= D:QuartzServiceQuartz.Net.Service.exe 完成服务创建
- 启动QuartzService服务可以看到D:QuartzService的日志文件有如下输出
2012-04-15 08:10:28,391 INFO Quartz.Impl.StdSchedulerFactory - Quartz.NET properties loaded from configuration file 'D:QuartzServicequartz.config' 2012-04-15 08:10:28,438 INFO Quartz.Impl.StdSchedulerFactory - Using default implementation for object serializer 2012-04-15 08:10:28,478 INFO Quartz.Impl.StdSchedulerFactory - Using default implementation for ThreadExecutor 2012-04-15 08:10:28,498 INFO Quartz.Core.SchedulerSignalerImpl - Initialized Scheduler Signaller of type: Quartz.Core.SchedulerSignalerImpl 2012-04-15 08:10:28,498 INFO Quartz.Core.QuartzScheduler - Quartz Scheduler v.2.0.0.400 created. 2012-04-15 08:10:28,502 INFO Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin - Registering Quartz Job Initialization Plug-in. 2012-04-15 08:10:28,517 INFO Quartz.Simpl.RAMJobStore - RAMJobStore initialized. 2012-04-15 08:10:28,540 INFO Quartz.Simpl.RemotingSchedulerExporter - Registering remoting channel of type 'System.Runtime.Remoting.Channels.Tcp.TcpChannel' to port (555) with name (httpQuartz) 2012-04-15 08:10:28,540 INFO Quartz.Simpl.RemotingSchedulerExporter - Remoting channel registered successfully 2012-04-15 08:10:28,541 INFO Quartz.Simpl.RemotingSchedulerExporter - Successfully marhalled remotable scheduler under name 'QuartzScheduler' 2012-04-15 08:10:28,543 INFO Quartz.Core.QuartzScheduler - Scheduler meta-data: Quartz Scheduler (v2.0.0.400) 'ServerScheduler' with instanceId 'NON_CLUSTERED' Scheduler class: 'Quartz.Core.QuartzScheduler' - access via remote incovation. NOT STARTED. Currently in standby mode. Number of jobs executed: 0 Using thread pool 'Quartz.Simpl.SimpleThreadPool' - with 10 threads. Using job-store 'Quartz.Simpl.RAMJobStore' - which does not support persistence. and is not clustered. 2012-04-15 08:10:28,543 INFO Quartz.Impl.StdSchedulerFactory - Quartz scheduler 'ServerScheduler' initialized 2012-04-15 08:10:28,543 INFO Quartz.Impl.StdSchedulerFactory - Quartz scheduler version: 2.0.0.400 2012-04-15 08:10:28,554 INFO Quartz.Xml.XMLSchedulingDataProcessor - Parsing XML file: D:QuartzServicequartz_jobs.xml with systemId: ~/quartz_jobs.xml 2012-04-15 08:10:28,930 INFO Quartz.Xml.XMLSchedulingDataProcessor - Adding 2 jobs, 3 triggers. 2012-04-15 08:10:28,933 INFO Quartz.Xml.XMLSchedulingDataProcessor - Adding job: DeomJobGroup.DemoJob1 2012-04-15 08:10:28,937 INFO Quartz.Xml.XMLSchedulingDataProcessor - Adding job: DeomJobGroup.DemoJob2 2012-04-15 08:10:28,997 INFO Quartz.Core.QuartzScheduler - Scheduler ServerScheduler_$_NON_CLUSTERED started. 2012-04-15 08:10:28,997 INFO Quartz.Net.Service.QuartzService - Quartz服务成功启动 2012-04-15 08:10:30,041 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 任务开始运行 2012-04-15 08:10:30,041 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行0 2012-04-15 08:10:30,041 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行1 2012-04-15 08:10:30,041 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行2 2012-04-15 08:10:30,041 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行3 2012-04-15 08:10:30,041 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行4 2012-04-15 08:10:30,041 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行5 2012-04-15 08:10:30,041 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行6 2012-04-15 08:10:30,041 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行7 2012-04-15 08:10:30,041 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行8 2012-04-15 08:10:30,041 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行9 2012-04-15 08:10:30,041 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1任务运行结束 2012-04-15 08:11:00,002 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 任务开始运行 2012-04-15 08:11:00,002 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行0 2012-04-15 08:11:00,002 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行1 2012-04-15 08:11:00,002 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行2 2012-04-15 08:11:00,002 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行3 2012-04-15 08:11:00,002 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行4 2012-04-15 08:11:00,003 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行5 2012-04-15 08:11:00,003 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行6 2012-04-15 08:11:00,003 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行7 2012-04-15 08:11:00,003 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行8 2012-04-15 08:11:00,003 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行9 2012-04-15 08:11:00,003 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1任务运行结束 2012-04-15 08:11:00,003 INFO Quartz.Net.Demo.DemoJob2 - DemoJob2 任务开始运行 2012-04-15 08:11:00,004 INFO Quartz.Net.Demo.DemoJob2 - DemoJob2 正在运行0 2012-04-15 08:11:00,004 INFO Quartz.Net.Demo.DemoJob2 - DemoJob2 正在运行1 2012-04-15 08:11:00,004 INFO Quartz.Net.Demo.DemoJob2 - DemoJob2 正在运行2 2012-04-15 08:11:00,004 INFO Quartz.Net.Demo.DemoJob2 - DemoJob2 正在运行3 2012-04-15 08:11:00,004 INFO Quartz.Net.Demo.DemoJob2 - DemoJob2 正在运行4 2012-04-15 08:11:00,004 INFO Quartz.Net.Demo.DemoJob2 - DemoJob2 正在运行5 2012-04-15 08:11:00,004 INFO Quartz.Net.Demo.DemoJob2 - DemoJob2 正在运行6 2012-04-15 08:11:00,004 INFO Quartz.Net.Demo.DemoJob2 - DemoJob2 正在运行7 2012-04-15 08:11:00,004 INFO Quartz.Net.Demo.DemoJob2 - DemoJob2 正在运行8 2012-04-15 08:11:00,004 INFO Quartz.Net.Demo.DemoJob2 - DemoJob2 正在运行9 2012-04-15 08:11:00,005 INFO Quartz.Net.Demo.DemoJob2 - DemoJob2任务运行结束 2012-04-15 08:11:29,999 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 任务开始运行 2012-04-15 08:11:29,999 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行0 2012-04-15 08:11:29,999 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行1 2012-04-15 08:11:29,999 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行2 2012-04-15 08:11:29,999 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行3 2012-04-15 08:11:29,999 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行4 2012-04-15 08:11:29,999 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行5 2012-04-15 08:11:29,999 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行6 2012-04-15 08:11:29,999 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行7 2012-04-15 08:11:29,999 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行8 2012-04-15 08:11:30,000 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1 正在运行9 2012-04-15 08:11:30,000 INFO Quartz.Net.Demo.DemoJob1 - DemoJob1任务运行结束 2012-04-15 08:11:32,607 INFO Quartz.Core.QuartzScheduler - Scheduler ServerScheduler_$_NON_CLUSTERED shutting down. 2012-04-15 08:11:32,608 INFO Quartz.Core.QuartzScheduler - Scheduler ServerScheduler_$_NON_CLUSTERED paused. 2012-04-15 08:11:32,611 INFO Quartz.Simpl.RemotingSchedulerExporter - Successfully disconnected remotable scheduler 2012-04-15 08:11:32,612 INFO Quartz.Core.QuartzScheduler - Scheduler ServerScheduler_$_NON_CLUSTERED Shutdown complete. 2012-04-15 08:11:32,612 INFO Quartz.Net.Service.QuartzService - Quartz服务成功终止
日志记录时可以根据需要使用Common.logging或者log4net,因为Quartz.Net使用的Common.logging的log4net实现,所以必须同时引用这两个dll,具体项目中引用这两个任意一个效果都是一样的(在使用log4net的前提下)
PS:
有很多人问Quartz启动后,关闭服务时无法及时关闭,必须杀进程才可以,解决方法时在调用Shutdown方法时传入参数false,即不等待任务运行结束立即关闭
scheduler.Shutdown(false);