概述
Quartz.NET是一個開源的做業調度框架,很是適合在平時的工做中,定時輪詢數據庫同步,定時郵件通知,定時處理數據等。 Quartz.NET容許開發人員根據時間間隔(或天)來調度做業。它實現了做業和觸發器的多對多關係,還能把多個做業與不一樣的觸發器關聯。整合了 Quartz.NET的應用程序能夠重用來自不一樣事件的做業,還能夠爲一個事件組合多個做業。html
下載下來官方的例子,咱們來分析一下:
解壓後,看到的文檔git
打開後,看到的項目結構以下:github
項目能夠直接運行:數據庫
運行後,咱們能夠看到,每隔10秒有輸出,那是由於,在配置quart.net的服務文件裏,配置了每10秒執行一次express
快速搭建一個Quartz
能夠不用本身搭建,官方的例子直接用就能夠windows
下面以2.6.1爲例app
第一步:安裝
新建一個QuartzDemo項目後,安裝下面的程序包框架
Install-Package Quartz
Install-Package Common.Logging.Log4Net1211
Install-Package log4net
Install-Package
Topshelf
Install-Package Topshelf.Log4Net
Quartz依賴Common.Logging和Common.Logging.Log4Net1211,又由於Log4Net是比較標準的日誌工具,所以咱們通常都會安裝log4net
,另外定時做業通常都容許在後臺服務中,所以咱們也安裝了Topshelf。async
由於版本之間的依賴,分別安裝可能會出問題,建議直接複製下面的Nuget配置,而後手動添加引用,或者安裝下面對應的版本tcp
<?xml version="1.0" encoding="utf-8"?> <packages> <package id="Common.Logging" version="3.3.1" targetFramework="net4" /> <package id="Common.Logging.Core" version="3.3.1" targetFramework="net4" /> <package id="Common.Logging.Log4Net1213" version="3.3.1" targetFramework="net4" /> <package id="log4net" version="2.0.3" targetFramework="net4" /> <package id="Quartz" version="2.6.1" targetFramework="net4" /> <package id="Topshelf" version="3.1.4" targetFramework="net4" /> </packages>
第二步:實現IJob
SampleJob.cs 實現IJob,在Execute方法裏編寫要處理的業務邏輯,系統就會按照Quartz的配置,定時處理。
using log4net; using Quartz; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JobLibrary { public class MyJob : IJob { private static readonly ILog logger = LogManager.GetLogger(typeof(MyJob)); public void Execute(IJobExecutionContext context) { logger.Info("MyJob running..."); //Thread.Sleep(TimeSpan.FromSeconds(5)); //logger.Info("SampleJob run finished."); } } }
第三步:使用Topshelf調度任務
QuartzServer.cs
using log4net; using Quartz; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Topshelf; namespace JobLibrary { public class QuartzServer : ServiceControl { private readonly ILog logger; private ISchedulerFactory schedulerFactory; private IScheduler scheduler; /// <summary> /// Initializes a new instance of the <see cref="QuartzServer"/> class. /// </summary> public QuartzServer() { logger = LogManager.GetLogger(GetType()); } /// <summary> /// Initializes the instance of the <see cref="QuartzServer"/> class. /// </summary> public virtual void Initialize() { try { schedulerFactory = CreateSchedulerFactory(); scheduler = GetScheduler(); } catch (Exception e) { logger.Error("Server initialization failed:" + e.Message, e); throw; } } /// <summary> /// Gets the scheduler with which this server should operate with. /// </summary> /// <returns></returns> protected virtual IScheduler GetScheduler() { return schedulerFactory.GetScheduler(); } /// <summary> /// Returns the current scheduler instance (usually created in <see cref="Initialize" /> /// using the <see cref="GetScheduler" /> method). /// </summary> protected virtual IScheduler Scheduler { get { return scheduler; } } /// <summary> /// Creates the scheduler factory that will be the factory /// for all schedulers on this instance. /// </summary> /// <returns></returns> protected virtual ISchedulerFactory CreateSchedulerFactory() { return new StdSchedulerFactory(); } /// <summary> /// Starts this instance, delegates to scheduler. /// </summary> public virtual void Start() { try { scheduler.Start(); } catch (Exception ex) { logger.Fatal(string.Format("Scheduler start failed: {0}", ex.Message), ex); throw; } logger.Info("Scheduler started successfully"); } /// <summary> /// Stops this instance, delegates to scheduler. /// </summary> public virtual void Stop() { try { scheduler.Shutdown(true); } catch (Exception ex) { logger.Error(string.Format("Scheduler stop failed: {0}", ex.Message), ex); throw; } logger.Info("Scheduler shutdown complete"); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public virtual void Dispose() { // no-op for now } /// <summary> /// Pauses all activity in scheduler. /// </summary> public virtual void Pause() { scheduler.PauseAll(); } /// <summary> /// Resumes all activity in server. /// </summary> public void Resume() { scheduler.ResumeAll(); } /// <summary> /// TopShelf's method delegated to <see cref="Start()"/>. /// </summary> public bool Start(HostControl hostControl) { Start(); return true; } /// <summary> /// TopShelf's method delegated to <see cref="Stop()"/>. /// </summary> public bool Stop(HostControl hostControl) { Stop(); return true; } /// <summary> /// TopShelf's method delegated to <see cref="Pause()"/>. /// </summary> public bool Pause(HostControl hostControl) { Pause(); return true; } /// <summary> /// TopShelf's method delegated to <see cref="Resume()"/>. /// </summary> public bool Continue(HostControl hostControl) { Resume(); return true; } } }
第四步:程序入口
using log4net; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Topshelf; namespace JobLibrary { class Program { static void Main(string[] args) { Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory); HostFactory.Run(x => { x.RunAsLocalSystem(); x.SetDescription("SetDescription"); x.SetDisplayName("SetDisplayName"); x.SetServiceName("SetServiceName"); x.Service(factory => { QuartzServer server = CreateServer(); server.Initialize(); return server; }); }); } private static readonly ILog logger = LogManager.GetLogger(typeof(Program)); /// <summary> /// Creates a new instance of an Quartz.NET server core. /// </summary> /// <returns></returns> public static QuartzServer CreateServer() { string typeName = typeof(QuartzServer).AssemblyQualifiedName; Type t = Type.GetType(typeName, true); logger.Debug("Creating new instance of server type '" + typeName + "'"); QuartzServer retValue = (QuartzServer)Activator.CreateInstance(t); logger.Debug("Instance successfully created"); return retValue; } } }
第五步:配置文件
quartz.config、quartz_jobs.xml、 log4net.conf
說明:這三個文件,分別選中→右鍵屬性→複製到輸入目錄設爲:始終複製
quartz.config
# 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 = 10 quartz.threadPool.threadPriority = Normal # 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 = 555 quartz.scheduler.exporter.bindName = QuartzScheduler quartz.scheduler.exporter.channelType = tcp quartz.scheduler.exporter.channelName = httpQuartz
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> <!--若是多個任務就配置多個Job/trigger--> <job> <name>MyJob</name> <group>sampleGroup</group> <description>Sample job for Quartz Server</description> <job-type>JobLibrary.MyJob, JobLibrary</job-type> <durable>true</durable> <recover>false</recover> </job> <trigger> <simple> <name>MyJobTrigger</name> <group>sampleSimpleGroup</group> <description>Simple trigger to simply fire sample job</description> <job-name>MyJob</job-name> <job-group>sampleGroup</job-group> <misfire-instruction>SmartPolicy</misfire-instruction> <repeat-count>-1</repeat-count> <repeat-interval>500</repeat-interval> </simple> </trigger> </schedule> </job-scheduling-data>
App.config
<?xml version="1.0" encoding="utf-8" ?> <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.Log4net1213"> <arg key="configType" value="INLINE" /> </factoryAdapter> </logging> </common> <log4net> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%d - %m%n" /> </layout> </appender> <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender"> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%d [%t] %-5p %l - %m%n" /> </layout> </appender> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <!--日誌路徑--> <param name= "File" value= "C:\App_Log\servicelog\"/> <!--是不是向文件中追加日誌--> <param name= "AppendToFile" value= "true"/> <!--log保留天數--> <param name= "MaxSizeRollBackups" value= "10"/> <!--日誌文件名是不是固定不變的--> <param name= "StaticLogFileName" value= "false"/> <!--日誌文件名格式爲:2008-08-31.log--> <param name= "DatePattern" value= "yyyy-MM-dd".read.log""/> <!--日誌根據日期滾動--> <param name= "RollingStyle" value= "Date"/> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n %loggername" /> </layout> </appender> <root> <level value="INFO" /> <!--<appender-ref ref="RollingLogFileAppender" />--> <appender-ref ref="ConsoleAppender" /> <!-- uncomment to enable event log appending --> <!-- <appender-ref ref="EventLogAppender" /> --> </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> --> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Common.Logging" publicKeyToken="af08829b84f0328e" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-3.3.1.0" newVersion="3.3.1.0" /> </dependentAssembly> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="log4net" publicKeyToken="669e0ddf0bb1aa2a" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-1.2.11.0" newVersion="1.2.11.0" /> </dependentAssembly> </assemblyBinding> <dependentAssembly> <assemblyIdentity name="Common.Logging.Core" publicKeyToken="af08829b84f0328e" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-3.3.1.0" newVersion="3.3.1.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="log4net" publicKeyToken="669e0ddf0bb1aa2a" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-1.2.12.0" newVersion="1.2.12.0" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration>
運行後,效果下圖,每隔0.5秒有輸出
項目結構
第六步:配置windows服務
添加項目:
項目結構
Service1.cs
using log4net; using Quartz; using Quartz.Impl; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; namespace JobService { public partial class Service1 : ServiceBase { private IScheduler scheduler; private readonly ILog logger; public Service1() { InitializeComponent(); ISchedulerFactory schedulerFactory = new StdSchedulerFactory(); scheduler = schedulerFactory.GetScheduler(); logger = LogManager.GetLogger(GetType()); } protected override void OnStart(string[] args) { logger.Info("Quartz服務成功啓動"); scheduler.Start(); } protected override void OnStop() { scheduler.Shutdown(false); } } }
而後把 app.config quartz_jobs.xml quartz.config 複製到該項目 quartz_jobs.xml quartz.config 設置爲始終複製
把app.config中 log4net配置改成文件模式
<root> <level value="INFO" /> <appender-ref ref="RollingLogFileAppender" /> <!--<appender-ref ref="ConsoleAppender" />--> <!-- uncomment to enable event log appending --> <!-- <appender-ref ref="EventLogAppender" /> --> </root>
編譯後找到bin目錄下exe註冊服務
註冊服務
注意: 等號後面必定要有空格
c:\>sc create qj1 binpath= "C:\Users\windows7\Desktop\QuartzDemo\QuartzDemo\JobSe
rvice\bin\Release\JobService.exe"
啓動服務 能夠設置爲自動 之後開機自動啓動
查看效果
卸載服務
sc delete MyJob
Quartz配置
quartz_jobs.xml
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(選填) 觸發器組d
- escription(選填) 觸發器描述
- 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秒執行一次
Quartz的cron表達式
官方英文介紹地址:http://www.quartz-scheduler.net/documentation/quartz-2.x/tutorial/crontrigger.html
cron expressions 總體上仍是很是容易理解的,只有一點須要注意:"?"號的用法,看下文能夠知道「?」能夠用在 day of month 和 day of week中,他主要是爲了解決以下場景,如:每個月的1號的每小時的31分鐘,正確的表達式是:* 31 * 1 * ?,而不能是:* 31 * 1 * *,由於這樣表明每週的任意一天。
由7段構成:秒 分 時 日 月 星期 年(可選)
"-" :表示範圍 MON-WED表示星期一到星期三
"," :表示列舉 MON,WEB表示星期一和星期三
"*" :表是「每」,每個月,天天,每週,每一年等
"/" :表示增量:0/15(處於分鐘段裏面) 每15分鐘,在0分之後開始,3/20 每20分鐘,從3分鐘之後開始
"?" :只能出如今日,星期段裏面,表示不指定具體的值
"L" :只能出如今日,星期段裏面,是Last的縮寫,一個月的最後一天,一個星期的最後一天(星期六)
"W" :表示工做日,距離給定值最近的工做日
"#" :表示一個月的第幾個星期幾,例如:"6#3"表示每月的第三個星期五(1=SUN...6=FRI,7=SAT)
官方實例
Expression | Meaning |
---|---|
0 0 12 * * ? | 天天中午12點觸發 |
0 15 10 ? * * | 天天上午10:15觸發 |
0 15 10 * * ? | 天天上午10:15觸發 |
0 15 10 * * ? * | 天天上午10:15觸發 |
0 15 10 * * ? 2005 | 2005年的天天上午10:15觸發 |
0 * 14 * * ? | 在天天下午2點到下午2:59期間的每1分鐘觸發 |
0 0/5 14 * * ? | 在天天下午2點到下午2:55期間的每5分鐘觸發 |
0 0/5 14,18 * * ? | 在天天下午2點到2:55期間和下午6點到6:55期間的每5分鐘觸發 |
0 0-5 14 * * ? | 在天天下午2點到下午2:05期間的每1分鐘觸發 |
0 10,44 14 ? 3 WED | 每一年三月的星期三的下午2:10和2:44觸發 |
0 15 10 ? * MON-FRI | 週一至週五的上午10:15觸發 |
0 15 10 15 * ? | 每個月15日上午10:15觸發 |
0 15 10 L * ? | 每個月最後一日的上午10:15觸發 |
0 15 10 L-2 * ? | Fire at 10:15am on the 2nd-to-last last day of every month |
0 15 10 ? * 6L | 每個月的最後一個星期五上午10:15觸發 |
0 15 10 ? * 6L | Fire at 10:15am on the last Friday of every month |
0 15 10 ? * 6L 2002-2005 | 2002年至2005年的每個月的最後一個星期五上午10:15觸發 |
0 15 10 ? * 6#3 | 每個月的第三個星期五上午10:15觸發 |
0 0 12 1/5 * ? | Fire at 12pm (noon) every 5 days every month, starting on the first day of the month. |
0 11 11 11 11 ? | Fire every November 11th at 11:11am. |
Quartz.NET 3.0 正式發佈
轉自:https://www.cnblogs.com/shanyou/p/8269641.html