淺談Quartz.Net 從無到有創建實例


一、Quartz.Net介紹

  Quartz.NET是一個開源的作業調度框架,非常適合在平時的工作中,定時輪詢數據庫同步,定時郵件通知,定時處理數據等。 Quartz.NET允許開發人員根據時間間隔(或天)來調度作業。它實現了作業和觸發器的多對多關系,還能把多個作業與不同的觸發器關聯。整合了 Quartz.NET的應用程序可以重用來自不同事件的作業,還可以為一個事件組合多個作業。在我平時的工作中對於Quartz的使用比較頻繁,正好利用空閑時間把這個做一個記錄。

二、快速搭建

1.利用VS創建一個控制台的項目

2.利用NuGet工具包安裝所需要的依賴包

3.首先安裝:Quartz,這里選擇我的項目一直在用的2.6的版本,目前為止最新的已經到了3.x

安裝完成之后在引用里面會多了一些新的引用

 

4.安裝我們的日志依賴包:log4net

5.安裝搭建服務用的:Topshelf 以及其所依賴的 Topshelf.Log4Net

 

至此,所用到的包基本已經安裝完畢,下面是添加三個程序文件和三個配置文件。

6.添加我們的測試程序文件:JobTest.cs,該文件實現Quartz的IJob接口

 1 using System;
 2 using log4net;
 3 using Quartz;
 4 
 5 namespace JobTest
 6 {
 7     public class TestJob : IJob
 8     {
 9         private readonly ILog _logger = LogManager.GetLogger(typeof(TestJob));
10         public void Execute(IJobExecutionContext context)
11         {
12             _logger.InfoFormat("測試輸出");
13         }
14     }
15 }
JobTest

7.添加用於Topshelf調度的文件:ServiceRunner.cs

 1 using Quartz;
 2 using Quartz.Impl;
 3 using Topshelf;
 4 
 5 namespace JobTest
 6 {
 7     public sealed class ServiceRunner : ServiceControl, ServiceSuspend
 8     {
 9         private readonly IScheduler scheduler;
10 
11         public ServiceRunner()
12         {
13             scheduler = StdSchedulerFactory.GetDefaultScheduler();
14         }
15 
16         public bool Start(HostControl hostControl)
17         {
18             scheduler.Start();
19             return true;
20         }
21 
22         public bool Stop(HostControl hostControl)
23         {
24             scheduler.Shutdown(false);
25             return true;
26         }
27 
28         public bool Continue(HostControl hostControl)
29         {
30             scheduler.ResumeAll();
31             return true;
32         }
33 
34         public bool Pause(HostControl hostControl)
35         {
36             scheduler.PauseAll();
37             return true;
38         }
39     }
40 }
ServiceRunner

8.添加程序的入口文件:Program.cs

 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 using Topshelf;
 8 
 9 namespace JobTest
10 {
11     class Program
12     {
13         static void Main(string[] args)
14         {
15             log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"));
16             HostFactory.Run(x =>
17             {
18                 x.UseLog4Net();
19 
20                 x.Service<ServiceRunner>();
21 
22                 x.SetDescription("定時作業");
23                 x.SetDisplayName("JobTest");
24                 x.SetServiceName("JobTest");
25 
26                 x.EnablePauseAndContinue();
27             });
28         }
29     }
30 }
Program.cs

9.添加配置文件:log4net.config

 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <configuration>
 3   <configSections>
 4     <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
 5   </configSections>
 6 
 7   <log4net>
 8     <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
 9       <!--日志路徑-->
10       <param name= "File" value= "D:\App_Log\servicelog\JobTest\"/>
11       <!--是否是向文件中追加日志-->
12       <param name= "AppendToFile" value= "true"/>
13       <!--log保留天數-->
14       <param name= "MaxSizeRollBackups" value= "10"/>
15       <!--日志文件名是否是固定不變的-->
16       <param name= "StaticLogFileName" value= "false"/>
17       <!--日志文件名格式為:2008-08-31.log-->
18       <param name= "DatePattern" value= "yyyy-MM-dd&quot;.read.log&quot;"/>
19       <!--日志根據日期滾動-->
20       <param name= "RollingStyle" value= "Date"/>
21       <layout type="log4net.Layout.PatternLayout">
22         <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n %loggername" />
23       </layout>
24     </appender>
25 
26     <!-- 控制台前台顯示日志 -->
27     <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
28       <mapping>
29         <level value="ERROR" />
30         <foreColor value="Red, HighIntensity" />
31       </mapping>
32       <mapping>
33         <level value="Info" />
34         <foreColor value="Green" />
35       </mapping>
36       <layout type="log4net.Layout.PatternLayout">
37         <conversionPattern value="%n%date{HH:mm:ss,fff} [%-5level] %m" />
38       </layout>
39 
40       <filter type="log4net.Filter.LevelRangeFilter">
41         <param name="LevelMin" value="Info" />
42         <param name="LevelMax" value="Fatal" />
43       </filter>
44     </appender>
45 
46     <root>
47       <!--(高) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (低) -->
48       <level value="all" />
49       <appender-ref ref="ColoredConsoleAppender"/>
50       <appender-ref ref="RollingLogFileAppender"/>
51     </root>
52   </log4net>
53 </configuration>
log4net.config

10.添加配置文件:quartz.config

 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 = QuartzTest
 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 = ~/quartz_jobs.xml
15 
16 # export this server to remoting context
17 #quartz.scheduler.exporter.type = Quartz.Simpl.RemotingSchedulerExporter, Quartz
18 #quartz.scheduler.exporter.port = 555
19 #quartz.scheduler.exporter.bindName = QuartzScheduler
20 #quartz.scheduler.exporter.channelType = tcp
21 #quartz.scheduler.exporter.channelName = httpQuartz
quartz.config

11.添加配置文件: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 
13     <!--TestJob測試 任務配置-->
14     <job>
15       <name>TestJob</name>
16       <group>Test</group>
17       <description>TestJob測試</description>
18       <job-type>JobTest.TestJob,JobTest</job-type>
19       <durable>true</durable>
20       <recover>false</recover>
21     </job>
22     <trigger>
23       <cron>
24         <name>TestJobTrigger</name>
25         <group>Test</group>
26         <job-name>TestJob</job-name>
27         <job-group>Test</job-group>
28         <start-time>2015-01-22T00:00:00+08:00</start-time>
29         <cron-expression>0/3 * * * * ?</cron-expression>
30       </cron>
31     </trigger>
32   </schedule>
33 </job-scheduling-data>
quartz_jobs.xml

注意:在這個xml文件中,job-type節點的配置容易出錯,我總結了一下,逗號之前的是我們將要運行的程序命名空間的地址

 

逗號之前:JobTest.TestJob

逗號之后是整個項目的命名空間,我們這里就是這個    JobTest

12.需要將三個配置文件的屬性設置為始終復制,或者如果較新則復制,應該也是沒問題的

 

13.啟動項目,就可以看到如下效果

 

三、搭建服務

1.將項目的生成方式切換成Release,至於Release和Debug的區別,可自行百度啦

然后重新生成項目

2.找到項目生成的文件夾,此時會發現一個JobTest.exe的文件,也是我們搭建服務所用的主文件

3.以管理員的身份運行cmd,並切換到上面程序生成的路徑,之后輸入JobTest.exe install 安裝服務:

 

4.啟動服務

 

5.此時,在我們的服務里就已經能看到我們創建的JobTest的服務了,並且已經啟動了:

 

6.此時,在我們之前的配置文件log4net.config中找到服務生成的日志文件的路徑,並切換到該路徑就可以看到生成的日志文件:

7.最后,友情提示,將服務關閉並卸載服務(JobTest.exe uninstall):

 

四、總結

  一個簡單的Quartz項目已經創建完成並生成了服務,可以定時去完成你指定的任何作業了。但是Quartz中還有一些問題非常重要。

  首先就是quartz_jobs.xml文件中cron-expression節點的配置,該節點的配置內容決定了服務的定時循環作業的頻率,詳情可見博客:https://blog.csdn.net/lu_wei_wei/article/details/51251337

  其次就是每次服務啟動,程序都會去運行一次,然后才會根據你設置的時間定時去運行,這樣很多時候是會有一些問題在里面的,具體的會在項目里面,遇到,到時候就需要用一些這種的方法去解決這些問題。

 

最后,盡情體驗Quartz.Net給你帶來的實現定時作業的快感吧!๑乛◡乛๑

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM