想必大家在項目中處理簡單的後台持續任務或者定時觸發任務的時候均使用 Thread 或者 Task 來完成,但是項目中的這種需求一旦多了的話就得將任務調度引入進來了,那今天就簡單的介紹一下 Quartz.NET 基於 Windows 服務宿主是怎樣配置使用的。
Quartz.NET 是一個優秀的任務調度框架,移植於 Java 版的 Quartz 。
官網:http://www.quartz-scheduler.net
Github:https://github.com/quartznet/quartznet
示例環境
- .Net 4.5.2
- Quartz 2.4.1
- Common.Logging 3.3.1
- log4net 2.0.5
- Common.Logging.Log4Net1213 3.3.1
源碼地址:https://github.com/Wlitsoft/QuartzNETWinServiceSample
配置
1. quartz.config
這個配置文件需要放在服務運行根目錄下,用於指定 quartz 的一些運行配置,比如調度名稱、線程池實現組件、線程池大小、任務配置文件路徑等。
1 # You can configure your scheduler in either <quartz> configuration section 2 # or in quartz properties file 3 # Configuration section has precedence 4 5 quartz.scheduler.instanceName = QuartzNETWinServiceScheduler 6 7 # configure thread pool info 8 quartz.threadPool.type = Quartz.Simpl.SimpleThreadPool, Quartz 9 quartz.threadPool.threadCount = 10 10 quartz.threadPool.threadPriority = Normal 11 12 # job initialization plugin handles our xml reading, without it defaults are used 13 quartz.plugin.xml.type = Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz 14 quartz.plugin.xml.fileNames = ~/Conf/jobs.config
暫時需求需要修改的只有一處,看最後一行 quartz.plugin.xml.fileNames = ~/Conf/jobs.config 指定任務的配置文件路徑。
2. 任務配置文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!-- This file contains job definitions in schema version 2.0 format --> 3 <job-scheduling-data xmlns="http://quartznet.sourceforge.net/JobSchedulingData" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"> 4 5 <processing-directives> 6 <overwrite-existing-data>true</overwrite-existing-data> 7 </processing-directives> 8 9 <schedule> 10 <job> 11 <name>Job1</name> 12 <group>Jobs</group> 13 <description>任務1</description> 14 <job-type>Wlitsoft.ProjectSample.QuartzNETWinService.Job.Job1,QuartzNETWinService</job-type> 15 <durable>true</durable> 16 <recover>false</recover> 17 </job> 18 <trigger> 19 <simple> 20 <name>Job1Trigger</name> 21 <group>Jobs</group> 22 <description>每 30 秒執行一次</description> 23 <job-name>Job1</job-name> 24 <job-group>Jobs</job-group> 25 <repeat-count>-1</repeat-count> 26 <repeat-interval>30000</repeat-interval> 27 </simple> 28 </trigger> 29 </schedule> 30 </job-scheduling-data>
以下為配置文件屬性:
- 任務 (job 節點)
job 節點項說明 名稱 類型 是否必填 默認值 描述 name string Y 任務名稱 group string N 默認組名 任務組名稱 description string N 任務描述 job-type string Y 任務的類型全名稱,一般實現 IJob 接口 durable boolean N false 任務完成後是否依然保存到數據庫 recover boolean N false 應用或服務重啟之後是否忽略過期任務
- 觸發器 (trigger 節點)
下面說下最常用的兩種觸發器:
1)簡單觸發器(simple 節點)用於觸發定時輪訓執行的任務。
simple 節點項說明 名稱 類型 是否必填 默認值 描述 name string Y 觸發器名稱 group string N 默認組名 觸發器名稱 description string N 觸發器描述 job-name string Y 要觸發的任務的名稱 job-group string Y 要觸發的任務的組名稱 repeat-count int Y 0 重復次數(0:不執行;-1:不限次數) repeat-interval long Y 0 間隔時間(單位:毫秒) start-time date N 當前時間 開始時間 end-time date N 結束時間(如果不指定則一直執行直到重復次數)
2)Cron 觸發器(cron 節點)根據 cron 表達式觸發任務。
cron 節點項說明 名稱 類型 是否必填 默認值 描述 name string Y 觸發器名稱 group string N 默認組名 觸發器名稱 description string N 觸發器描述 job-name string Y 要觸發的任務的名稱 job-group string Y 要觸發的任務的組名稱 cron string Y 規則表達式 start-time date N 當前時間 開始時間 end-time date N 結束時間
注:cron 表達式在線生成:http://cron.qqe2.com
3. 日志配置文件
1) app.config
- configSctions
1 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> 2 <sectionGroup name="common"> 3 <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" /> 4 </sectionGroup>
- commong.logging 配置
1 <common> 2 <logging> 3 <factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4Net1213"> 4 <arg key="configType" value="FILE-WATCH" /> 5 <arg key="configFile" value="~/Conf/log4net.config" /> 6 <arg key="level" value="INFO" /> 7 </factoryAdapter> 8 </logging> 9 </common>
- configType : 用於指定日子配置文件類型,取值:INLINE - 在當前配置文件總;FILE-WATCH - 配置文件中。
- configFile:配置文件路徑。
- level:日子輸出級別。
- log4net 配置

主程序代碼:
1 using System.ServiceProcess;
2 using Common.Logging;
3 using Quartz;
4 using Quartz.Impl;
5
6 namespace Wlitsoft.ProjectSample.QuartzNETWinService
7 {
8 public partial class MainService : ServiceBase
9 {
10 #region 私有屬性
11
12 //日志記錄這。
13 private readonly ILog _logger;
14
15 //調度器。
16 private readonly IScheduler _scheduler;
17
18 #endregion
19
20 #region 構造方法
21
22 /// <summary>
23 /// 初始化 <see cref="MainService"/> 類的新實例。
24 /// </summary>
25 public MainService()
26 {
27 InitializeComponent();
28 this._logger = LogManager.GetLogger(this.GetType());
29 StdSchedulerFactory factory = new StdSchedulerFactory();
30 this._scheduler = factory.GetScheduler();
31 }
32
33 #endregion
34
35 protected override void OnStart(string[] args)
36 {
37 this._scheduler.Start();
38 this._logger.Info("服務啟動");
39 }
40
41 protected override void OnStop()
42 {
43 if (!this._scheduler.IsShutdown)
44 this._scheduler.Shutdown();
45 this._logger.Info("服務停止");
46 }
47
48 protected override void OnPause()
49 {
50 this._scheduler.PauseAll();
51 base.OnPause();
52 }
53
54 protected override void OnContinue()
55 {
56 this._scheduler.ResumeAll();
57 base.OnContinue();
58 }
59 }
60 }
示例任務代碼:
1 using Common.Logging;
2 using Quartz;
3
4 namespace Wlitsoft.ProjectSample.QuartzNETWinService.Job
5 {
6 public class Job1 : IJob
7 {
8 //日志構造者。
9 private static readonly ILog Logger = LogManager.GetLogger("job1");
10
11 #region Implementation of IJob
12
13 /// <summary>
14 /// Called by the <see cref="T:Quartz.IScheduler" /> when a <see cref="T:Quartz.ITrigger" />
15 /// fires that is associated with the <see cref="T:Quartz.IJob" />.
16 /// </summary>
17 /// <remarks>
18 /// The implementation may wish to set a result object on the
19 /// JobExecutionContext before this method exits. The result itself
20 /// is meaningless to Quartz, but may be informative to
21 /// <see cref="T:Quartz.IJobListener" />s or
22 /// <see cref="T:Quartz.ITriggerListener" />s that are watching the job's
23 /// execution.
24 /// </remarks>
25 /// <param name="context">The execution context.</param>
26 public void Execute(IJobExecutionContext context)
27 {
28 string jobDes = context.JobDetail.Description;
29 Logger.Info($"{jobDes}運行");
30 }
31
32 #endregion
33 }
34 }
源碼地址:https://github.com/Wlitsoft/QuartzNETWinServiceSample
推薦閱讀:一個技術汪的開源夢