Quartz.NET 项目地址 http://quartznet.sourceforge.net/

Quartz.NET 2.0 学习笔记(1) :Quartz.NET简介

Quartz.NET 2.0 学习笔记(2) :和1.0的几点不同

Quartz.NET 2.0 学习笔记(3) :通过配置文件实现任务调度

Quartz.NET 2.0 学习笔记(4) :cron表达式

Quartz.NET 2.0 学习笔记(5) :实例创建Windows服务实现任务调度

 

使用普通Windows服务创建Quartz.Net服务项目

  1. 首先创建Quartz.Net.2.0解决方案,添加 Windows服务 项目,添加安装程序,修改服务运行账户类型为LocalSystem(默认为User)
  2. 添加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 小白都知道不解释

  3. 添加quartz.config文件 Quartz.Net的配置文件,并设置编译时生成到输出目录为始终复制
  4. Windows服务文件上右键查看代码,编写Quartz服务启动代码,重写OnStart、OnStop、OnPause、OnContinue方法,分别对应IScheduler的Start、Shutdown、PauseAll、ResumeAll方法,详见代码
    1. using System.ServiceProcess;  
    2. using Common.Logging;  
    3. using Quartz.Impl;  
    4.   
    5. namespace Quartz.Net.Service  
    6. {  
    7.     public partial class QuartzService : ServiceBase  
    8.     {  
    9.         private readonly ILog logger;  
    10.         private IScheduler scheduler;  
    11.   
    12.         public QuartzService()  
    13.         {  
    14.             InitializeComponent();  
    15.             logger = LogManager.GetLogger(GetType());  
    16.             ISchedulerFactory schedulerFactory = new StdSchedulerFactory();  
    17.             scheduler = schedulerFactory.GetScheduler();  
    18.         }  
    19.   
    20.         protected override void OnStart(string[] args)  
    21.         {  
    22.             scheduler.Start();  
    23.             logger.Info("Quartz服务成功启动");  
    24.         }  
    25.   
    26.         protected override void OnStop()  
    27.         {  
    28.             scheduler.Shutdown();  
    29.             logger.Info("Quartz服务成功终止");  
    30.         }  
    31.   
    32.         protected override void OnPause()  
    33.         {  
    34.             scheduler.PauseAll();  
    35.         }  
    36.   
    37.         protected override void OnContinue()  
    38.         {  
    39.             scheduler.ResumeAll();  
    40.         }  
    41.         
    42.     }  
    43. }  

至此Quarzt.Net 的Windows服务已成功创建,接下创建实现了IJob接口Quartz任务

  1. 添加Quartz.Net.Demo类库项目
  2. 添加Common.Logging.dll、log4net.dll、Quartz.dll的引用(实际项目中Common.Logging.dll和log4net.dll任意引用一个即可,此处为演示需要)
  3. 添加DemoJob1.cs,实现IJob接口,日志记录使用Common.Logging接口
    1. using System;  
    2.   
    3. namespace Quartz.Net.Demo  
    4. {  
    5.     /// <summary>  
    6.     /// 实现IJob接口  
    7.     /// </summary>  
    8.     public class DemoJob1 : IJob  
    9.     {  
    10.         //使用Common.Logging.dll日志接口实现日志记录  
    11.         private static readonly Common.Logging.ILog logger = Common.Logging.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);  
    12.         #region IJob 成员  
    13.   
    14.         public void Execute(IJobExecutionContext context)  
    15.         {  
    16.             try  
    17.             {  
    18.                 logger.Info("DemoJob1 任务开始运行");  
    19.   
    20.                 for (int i = 0; i < 10; i++)  
    21.                 {  
    22.                     logger.InfoFormat("DemoJob1 正在运行{0}", i);  
    23.                 }  
    24.   
    25.                 logger.Info("DemoJob1任务运行结束");  
    26.             }  
    27.             catch (Exception ex)  
    28.             {  
    29.                 logger.Error("DemoJob2 运行异常", ex);  
    30.             }  
    31.   
    32.         }  
    33.  
    34.         #endregion  
    35.     }  
    36. }  

  4. 添加DemoJob2.cs,实现IJob接口,日志记录使用log4net
    1. using System;  
    2.   
    3. namespace Quartz.Net.Demo  
    4. {  
    5.     /// <summary>  
    6.     /// 实现IJob接口  
    7.     /// </summary>  
    8.     public class DemoJob2 : IJob  
    9.     {  
    10.         //使用log4net.dll日志接口实现日志记录  
    11.         private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);  
    12.         #region IJob 成员  
    13.   
    14.         public void Execute(IJobExecutionContext context)  
    15.         {  
    16.             try  
    17.             {  
    18.                 logger.Info("DemoJob2 任务开始运行");  
    19.   
    20.                 for (int i = 0; i < 10; i++)  
    21.                 {  
    22.                     logger.InfoFormat("DemoJob2 正在运行{0}", i);  
    23.                 }  
    24.   
    25.                 logger.Info("DemoJob2任务运行结束");  
    26.             }  
    27.             catch (Exception ex)  
    28.             {  
    29.                 logger.Error("DemoJob2 运行异常", ex);  
    30.             }  
    31.   
    32.         }  
    33.  
    34.         #endregion  
    35.     }  
    36. }  

  5. 添加quartz_jobs.xml(配置调度任务)
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2.   
    3. <!-- This file contains job definitions in schema version 2.0 format -->  
    4.   
    5. <job-scheduling-data xmlns="http://quartznet.sourceforge.net/JobSchedulingData" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0">  
    6.   
    7.   <processing-directives>  
    8.     <overwrite-existing-data>true</overwrite-existing-data>  
    9.   </processing-directives>  
    10.   
    11.   <schedule>  
    12.     <!--定义示例任务1 Job-->  
    13.     <job>  
    14.       <name>DemoJob1</name>  
    15.       <group>DeomJobGroup</group>  
    16.       <description>Quartz.Net示例任务1</description>  
    17.       <job-type>Quartz.Net.Demo.DemoJob1,Quartz.Net.Demo</job-type>  
    18.       <durable>true</durable>  
    19.       <recover>false</recover>  
    20.     </job>  
    21.   
    22.     <!--定义示例任务2 Job-->  
    23.     <job>  
    24.       <name>DemoJob2</name>  
    25.       <group>DeomJobGroup</group>  
    26.       <description>Quartz.Net示例任务2</description>  
    27.       <job-type>Quartz.Net.Demo.DemoJob2,Quartz.Net.Demo</job-type>  
    28.       <durable>true</durable>  
    29.       <recover>false</recover>  
    30.     </job>  
    31.   
    32.     <!--定义示例任务1 触发器 每30秒执行一次DemoJob1任务-->  
    33.     <trigger>  
    34.       <cron>  
    35.         <name>DemoJob1Trigger</name>  
    36.         <group>DeomJobTriggerGroup</group>  
    37.         <job-name>DemoJob1</job-name>  
    38.         <job-group>DeomJobGroup</job-group>  
    39.         <cron-expression>0/30 * * * * ?</cron-expression>  
    40.       </cron>  
    41.     </trigger>  
    42.   
    43.     <!--定义示例任务2 触发器 每分钟执行一次DemoJob2任务-->  
    44.     <trigger>  
    45.       <cron>  
    46.         <name>DemoJob2Trigger1</name>  
    47.         <group>DeomJobTriggerGroup</group>  
    48.         <job-name>DemoJob2</job-name>  
    49.         <job-group>DeomJobGroup</job-group>  
    50.         <cron-expression>0 * * * * ?</cron-expression>  
    51.       </cron>  
    52.     </trigger>  
    53.   
    54.     <!--定义示例任务2 触发器 每天凌晨01:00执行一次DemoJob2任务-->  
    55.     <trigger>  
    56.       <cron>  
    57.         <name>DemoJob2Trigger2</name>  
    58.         <group>DeomJobTriggerGroup</group>  
    59.         <job-name>DemoJob2</job-name>  
    60.         <job-group>DeomJobGroup</job-group>  
    61.         <cron-expression>0 0 1 * * ?</cron-expression>  
    62.       </cron>  
    63.     </trigger>  
    64.   </schedule>  
    65. </job-scheduling-data>  

  6. 修改app.config,配置Common.logging、log4net
    1. <?xml version="1.0"?>  
    2. <configuration>  
    3.   <configSections>  
    4.     <section name="quartz" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089"/>  
    5.     <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>  
    6.     <sectionGroup name="common">  
    7.       <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging"/>  
    8.     </sectionGroup>  
    9.   </configSections>  
    10.   <common>  
    11.     <logging>  
    12.       <factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4net">  
    13.         <arg key="configType" value="INLINE"/>  
    14.       </factoryAdapter>  
    15.     </logging>  
    16.   </common>  
    17.   <log4net>  
    18.     <appender name="InfoFileAppender" type="log4net.Appender.RollingFileAppender">  
    19.       <file value="log/" />  
    20.       <appendToFile value="true" />  
    21.       <param name="DatePattern" value="yyyyMMdd".txt"" />  
    22.       <rollingStyle value="Date" />  
    23.       <maxSizeRollBackups value="100" />  
    24.       <maximumFileSize value="1024KB" />  
    25.       <staticLogFileName value="false" />  
    26.       <Encoding value="UTF-8" />  
    27.       <filter type="log4net.Filter.LevelRangeFilter">  
    28.         <param name="LevelMin" value="INFO" />  
    29.         <param name="LevelMax" value="INFO" />  
    30.       </filter>  
    31.       <layout type="log4net.Layout.PatternLayout">  
    32.         <conversionPattern value="%date %-5level %logger  - %message%newline" />  
    33.       </layout>  
    34.     </appender>  
    35.     <appender name="ErrorFileAppender" type="log4net.Appender.RollingFileAppender">  
    36.       <file value="log/error.txt" />  
    37.       <appendToFile value="true" />  
    38.       <rollingStyle value="Size" />  
    39.       <maxSizeRollBackups value="100" />  
    40.       <maximumFileSize value="10240KB" />  
    41.       <staticLogFileName value="true" />  
    42.       <Encoding value="UTF-8" />  
    43.       <filter type="log4net.Filter.LevelRangeFilter">  
    44.         <param name="LevelMin" value="WARN" />  
    45.         <param name="LevelMax" value="FATAL" />  
    46.       </filter>  
    47.       <layout type="log4net.Layout.PatternLayout">  
    48.         <conversionPattern value="%date %-5level %logger - %message%newline" />  
    49.       </layout>  
    50.     </appender>  
    51.     <root>  
    52.       <level value="INFO" />  
    53.       <appender-ref ref="InfoFileAppender" />  
    54.       <appender-ref ref="ErrorFileAppender" />  
    55.     </root>  
    56.   </log4net>  
    57.   
    58.   <!--   
    59.     We use quartz.config for this server, you can always use configuration section if you want to.  
    60.     Configuration section has precedence here.    
    61.   -->  
    62.   <!--  
    63.   <quartz >  
    64.   </quartz>  
    65.   -->  
    66.   <startup>  
    67.     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>  
    68.   </startup>  
    69. </configuration>  


Quartz.Net.Service和Quartz.Net.Demo均创建完毕后,进行编译然后把我们创建的Quartz服务添加到系统的服务中去

  1. 把编译好的如下文件拷贝到D:\QuartzService\ 
  2. 控制台下执行如下命令:sc create QuartzService binpath= D:\QuartzService\Quartz.Net.Service.exe 完成服务创建
  3. 启动QuartzService服务可以看到D:\QuartzService\的日志文件有如下输出
    1. 2012-04-15 08:10:28,391 INFO  Quartz.Impl.StdSchedulerFactory  - Quartz.NET properties loaded from configuration file 'D:\QuartzService\quartz.config'  
    2. 2012-04-15 08:10:28,438 INFO  Quartz.Impl.StdSchedulerFactory  - Using default implementation for object serializer  
    3. 2012-04-15 08:10:28,478 INFO  Quartz.Impl.StdSchedulerFactory  - Using default implementation for ThreadExecutor  
    4. 2012-04-15 08:10:28,498 INFO  Quartz.Core.SchedulerSignalerImpl  - Initialized Scheduler Signaller of type: Quartz.Core.SchedulerSignalerImpl  
    5. 2012-04-15 08:10:28,498 INFO  Quartz.Core.QuartzScheduler  - Quartz Scheduler v.2.0.0.400 created.  
    6. 2012-04-15 08:10:28,502 INFO  Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin  - Registering Quartz Job Initialization Plug-in.  
    7. 2012-04-15 08:10:28,517 INFO  Quartz.Simpl.RAMJobStore  - RAMJobStore initialized.  
    8. 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)  
    9. 2012-04-15 08:10:28,540 INFO  Quartz.Simpl.RemotingSchedulerExporter  - Remoting channel registered successfully  
    10. 2012-04-15 08:10:28,541 INFO  Quartz.Simpl.RemotingSchedulerExporter  - Successfully marhalled remotable scheduler under name 'QuartzScheduler'  
    11. 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'  
    12.   Scheduler class: 'Quartz.Core.QuartzScheduler' - access via remote incovation.  
    13.   NOT STARTED.  
    14.   Currently in standby mode.  
    15.   Number of jobs executed: 0  
    16.   Using thread pool 'Quartz.Simpl.SimpleThreadPool' - with 10 threads.  
    17.   Using job-store 'Quartz.Simpl.RAMJobStore' - which does not support persistence. and is not clustered.  
    18.   
    19. 2012-04-15 08:10:28,543 INFO  Quartz.Impl.StdSchedulerFactory  - Quartz scheduler 'ServerScheduler' initialized  
    20. 2012-04-15 08:10:28,543 INFO  Quartz.Impl.StdSchedulerFactory  - Quartz scheduler version: 2.0.0.400  
    21. 2012-04-15 08:10:28,554 INFO  Quartz.Xml.XMLSchedulingDataProcessor  - Parsing XML file: D:\QuartzService\quartz_jobs.xml with systemId: ~/quartz_jobs.xml  
    22. 2012-04-15 08:10:28,930 INFO  Quartz.Xml.XMLSchedulingDataProcessor  - Adding 2 jobs, 3 triggers.  
    23. 2012-04-15 08:10:28,933 INFO  Quartz.Xml.XMLSchedulingDataProcessor  - Adding job: DeomJobGroup.DemoJob1  
    24. 2012-04-15 08:10:28,937 INFO  Quartz.Xml.XMLSchedulingDataProcessor  - Adding job: DeomJobGroup.DemoJob2  
    25. 2012-04-15 08:10:28,997 INFO  Quartz.Core.QuartzScheduler  - Scheduler ServerScheduler_$_NON_CLUSTERED started.  
    26. 2012-04-15 08:10:28,997 INFO  Quartz.Net.Service.QuartzService  - Quartz服务成功启动  
    27. 2012-04-15 08:10:30,041 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 任务开始运行  
    28. 2012-04-15 08:10:30,041 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行0  
    29. 2012-04-15 08:10:30,041 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行1  
    30. 2012-04-15 08:10:30,041 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行2  
    31. 2012-04-15 08:10:30,041 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行3  
    32. 2012-04-15 08:10:30,041 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行4  
    33. 2012-04-15 08:10:30,041 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行5  
    34. 2012-04-15 08:10:30,041 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行6  
    35. 2012-04-15 08:10:30,041 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行7  
    36. 2012-04-15 08:10:30,041 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行8  
    37. 2012-04-15 08:10:30,041 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行9  
    38. 2012-04-15 08:10:30,041 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1任务运行结束  
    39. 2012-04-15 08:11:00,002 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 任务开始运行  
    40. 2012-04-15 08:11:00,002 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行0  
    41. 2012-04-15 08:11:00,002 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行1  
    42. 2012-04-15 08:11:00,002 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行2  
    43. 2012-04-15 08:11:00,002 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行3  
    44. 2012-04-15 08:11:00,002 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行4  
    45. 2012-04-15 08:11:00,003 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行5  
    46. 2012-04-15 08:11:00,003 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行6  
    47. 2012-04-15 08:11:00,003 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行7  
    48. 2012-04-15 08:11:00,003 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行8  
    49. 2012-04-15 08:11:00,003 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行9  
    50. 2012-04-15 08:11:00,003 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1任务运行结束  
    51. 2012-04-15 08:11:00,003 INFO  Quartz.Net.Demo.DemoJob2  - DemoJob2 任务开始运行  
    52. 2012-04-15 08:11:00,004 INFO  Quartz.Net.Demo.DemoJob2  - DemoJob2 正在运行0  
    53. 2012-04-15 08:11:00,004 INFO  Quartz.Net.Demo.DemoJob2  - DemoJob2 正在运行1  
    54. 2012-04-15 08:11:00,004 INFO  Quartz.Net.Demo.DemoJob2  - DemoJob2 正在运行2  
    55. 2012-04-15 08:11:00,004 INFO  Quartz.Net.Demo.DemoJob2  - DemoJob2 正在运行3  
    56. 2012-04-15 08:11:00,004 INFO  Quartz.Net.Demo.DemoJob2  - DemoJob2 正在运行4  
    57. 2012-04-15 08:11:00,004 INFO  Quartz.Net.Demo.DemoJob2  - DemoJob2 正在运行5  
    58. 2012-04-15 08:11:00,004 INFO  Quartz.Net.Demo.DemoJob2  - DemoJob2 正在运行6  
    59. 2012-04-15 08:11:00,004 INFO  Quartz.Net.Demo.DemoJob2  - DemoJob2 正在运行7  
    60. 2012-04-15 08:11:00,004 INFO  Quartz.Net.Demo.DemoJob2  - DemoJob2 正在运行8  
    61. 2012-04-15 08:11:00,004 INFO  Quartz.Net.Demo.DemoJob2  - DemoJob2 正在运行9  
    62. 2012-04-15 08:11:00,005 INFO  Quartz.Net.Demo.DemoJob2  - DemoJob2任务运行结束  
    63. 2012-04-15 08:11:29,999 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 任务开始运行  
    64. 2012-04-15 08:11:29,999 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行0  
    65. 2012-04-15 08:11:29,999 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行1  
    66. 2012-04-15 08:11:29,999 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行2  
    67. 2012-04-15 08:11:29,999 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行3  
    68. 2012-04-15 08:11:29,999 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行4  
    69. 2012-04-15 08:11:29,999 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行5  
    70. 2012-04-15 08:11:29,999 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行6  
    71. 2012-04-15 08:11:29,999 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行7  
    72. 2012-04-15 08:11:29,999 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行8  
    73. 2012-04-15 08:11:30,000 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行9  
    74. 2012-04-15 08:11:30,000 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1任务运行结束  
    75. 2012-04-15 08:11:32,607 INFO  Quartz.Core.QuartzScheduler  - Scheduler ServerScheduler_$_NON_CLUSTERED shutting down.  
    76. 2012-04-15 08:11:32,608 INFO  Quartz.Core.QuartzScheduler  - Scheduler ServerScheduler_$_NON_CLUSTERED paused.  
    77. 2012-04-15 08:11:32,611 INFO  Quartz.Simpl.RemotingSchedulerExporter  - Successfully disconnected remotable scheduler  
    78. 2012-04-15 08:11:32,612 INFO  Quartz.Core.QuartzScheduler  - Scheduler ServerScheduler_$_NON_CLUSTERED Shutdown complete.  
    79. 2012-04-15 08:11:32,612 INFO  Quartz.Net.Service.QuartzService  - Quartz服务成功终止  

日志记录时可以根据需要使用Common.logging或者log4net,因为Quartz.Net使用的Common.logging的log4net实现,所以必须同时引用这两个dll,具体项目中引用这两个任意一个效果都是一样的(在使用log4net的前提下)

源文件下载:Quartz-2.0Demo.rar

PS:

有很多人问Quartz启动后,关闭服务时无法及时关闭,必须杀进程才可以,解决方法时在调用Shutdown方法时传入参数false,即不等待任务运行结束立即关闭

scheduler.Shutdown(false);