詳細介紹Quartz.Net調度架構配置的執行個體

來源:互聯網
上載者:User
這篇文章主要為大家詳細介紹了Quartz.Net調度架構的配置方法,具有一定的參考價值,感興趣的小夥伴們可以參考一下

在平時的工作中,估計大多數都做過輪詢調度的任務,比如定時輪詢資料庫同步,定時郵件通知等等。大家通過windows計劃任務,windows服務等都實現過此類任務,甚至實現過自己的配置定製化的架構。那今天就來介紹個開源的調度架構Quartz.Net(主要介紹配置的實現,因為有朋友問過此類問題)。調度的實現代碼很簡單,在源碼中有大量Demo,這裡就略過了。

Quartz.Net當前最新版本Quartz.NET 2.0 beta 1 Released

一、基於檔案配置

先看一下簡單的實現代碼


using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using Quartz;using Quartz.Impl;using Common.Logging;namespace Demo{ class Program {  static void Main(string[] args)  {      // First we must get a reference to a scheduler   ISchedulerFactory sf = new StdSchedulerFactory();   IScheduler sched = sf.GetScheduler();      sched.Start();      sched.Shutdown(true);     } }}

代碼很簡單,設定檔中的quartz基礎配置,以及job,trigger資訊是如何載入的?這個過程是發生 IScheduler sched = sf.GetScheduler();過程,主要體現在源碼這一段


 public void Initialize()  {   // short-circuit if already initialized   if (cfg != null)   {    return;   }   if (initException != null)   {    throw initException;   }   NameValueCollection props = (NameValueCollection) ConfigurationManager.GetSection("quartz");   string requestedFile = Environment.GetEnvironmentVariable(PropertiesFile);   string propFileName = requestedFile != null && requestedFile.Trim().Length > 0 ? requestedFile : "~/quartz.config";   // check for specials   propFileName = FileUtil.ResolveFile(propFileName);   if (props == null && File.Exists(propFileName))   {    // file system    try    {     PropertiesParser pp = PropertiesParser.ReadFromFileResource(propFileName);     props = pp.UnderlyingProperties;     Log.Info(string.Format("Quartz.NET properties loaded from configuration file '{0}'", propFileName));    }    catch (Exception ex)    {     Log.Error("Could not load properties for Quartz from file {0}: {1}".FormatInvariant(propFileName, ex.Message), ex);    }   }   if (props == null)   {    // read from assembly    try    {     PropertiesParser pp = PropertiesParser.ReadFromEmbeddedAssemblyResource("Quartz.quartz.config");     props = pp.UnderlyingProperties;     Log.Info("Default Quartz.NET properties loaded from embedded resource file");    }    catch (Exception ex)    {     Log.Error("Could not load default properties for Quartz from Quartz assembly: {0}".FormatInvariant(ex.Message), ex);    }   }   if (props == null)   {    throw new SchedulerConfigException(     @"Could not find <quartz> configuration section from your application config or load default configuration from assembly.Please add configuration to your application config file to correctly initialize Quartz.");   }   Initialize(OverrideWithSysProps(props));  }

通過上面程式碼分析,初始化首先會檢查系統config中是否有<quartz> configuration section節點 (config指的app.config,web.config),如果系統config有quartz節點,則直接載入此處的配置資訊。如果系統config沒有quartz的基礎配置資訊,則會繼續尋找是否有quartz.config/Quartz.quartz.config 這兩個設定檔的存在,如果有則載入配置資訊,如果沒有則扔出初始化配置異常。

而jobs.xml(調度的任務和觸發器plugin節點設定檔)

app.config/web.config 中plugin配置


 <quartz>  <add key="quartz.scheduler.instanceName" value="ExampleDefaultQuartzScheduler"/>  <add key="quartz.threadPool.type" value="Quartz.Simpl.SimpleThreadPool, Quartz"/>  <add key="quartz.threadPool.threadCount" value="10"/>  <add key="quartz.threadPool.threadPriority" value="2"/>  <add key="quartz.jobStore.misfireThreshold" value="60000"/>  <add key="quartz.jobStore.type" value="Quartz.Simpl.RAMJobStore, Quartz"/> <!--******************************Plugin配置********************************************* --> <add key="quartz.plugin.xml.type" value="Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz" /> <add key="quartz.plugin.xml.fileNames" value="quartz_jobs.xml"/>  </quartz>

quartz.config 中plugin配置指向(quartz.plugin.xml.type / quartz.plugin.xml.fileNames)


# You can configure your scheduler in either <quartz> configuration section# or in quartz properties file# Configuration section has precedencequartz.scheduler.instanceName = ServerScheduler# configure thread pool infoquartz.threadPool.type = Quartz.Simpl.SimpleThreadPool, Quartzquartz.threadPool.threadCount = 10quartz.threadPool.threadPriority = Normal#--------------------------------*************plugin配置------------------------------------# job initialization plugin handles our xml reading, without it defaults are usedquartz.plugin.xml.type = Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartzquartz.plugin.xml.fileNames = ~/quartz_jobs.xml# export this server to remoting contextquartz.scheduler.exporter.type = Quartz.Simpl.RemotingSchedulerExporter, Quartzquartz.scheduler.exporter.port = 555quartz.scheduler.exporter.bindName = QuartzSchedulerquartz.scheduler.exporter.channelType = tcpquartz.scheduler.exporter.channelName = httpQuartz

二、基於代碼的方式

這種情況直接通過代碼實現的,官方DEMO很多都是如此,我們舉個例子


using System;using System.Collections.Generic;using System.Linq;using System.Text; using Quartz;using Quartz.Impl;using System.Threading;using Common.Logging;namespace Demo{ class Program {  static void Main(string[] args)  {   ILog log = LogManager.GetLogger(typeof(Demo.HelloJob));   log.Info("------- Initializing ----------------------");   // First we must get a reference to a scheduler   ISchedulerFactory sf = new StdSchedulerFactory();   IScheduler sched = sf.GetScheduler();   log.Info("------- Initialization Complete -----------");   //---------------------------------------代碼添加job和trigger   // computer a time that is on the next round minute   DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);   log.Info("------- Scheduling Job -------------------");   // define the job and tie it to our HelloJob class   IJobDetail job = JobBuilder.Create<HelloJob>()    .WithIdentity("job1", "group1")    .Build();   // Trigger the job to run on the next round minute   ITrigger trigger = TriggerBuilder.Create()    .WithIdentity("trigger1", "group1")    .StartAt(runTime)    .Build();   // Tell quartz to schedule the job using our trigger   sched.ScheduleJob(job, trigger);   log.Info(string.Format("{0} will run at: {1}", job.Key, runTime.ToString("r")));   // Start up the scheduler (nothing can actually run until the    // scheduler has been started)   sched.Start();   log.Info("------- Started Scheduler -----------------");   // wait long enough so that the scheduler as an opportunity to    // run the job!   log.Info("------- Waiting 65 seconds... -------------");   // wait 65 seconds to show jobs   Thread.Sleep(TimeSpan.FromSeconds(65));   // shut down the scheduler   log.Info("------- Shutting Down ---------------------");   sched.Shutdown(true);   log.Info("------- Shutdown Complete -----------------");  } }}

其實代碼方式已經實現了和設定檔混搭的方式了。但是這種對方式是通過配置關聯載入job與trigger配置,我們還有第三種方式,自己載入job與trigger設定檔。

三、手動載入設定檔


using System;using System.Collections.Generic;using System.Linq;using System.Text; using Quartz;using Quartz.Xml;using Quartz.Impl;using Quartz.Simpl;using System.Threading;using Common.Logging;using System.IO;namespace Demo{ class Program {  static void Main(string[] args)  {       XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper());   ISchedulerFactory sf = new StdSchedulerFactory();   IScheduler scheduler = sf.GetScheduler();   Stream s = new StreamReader("~/quartz.xml").BaseStream;   processor.ProcessStream(s, null);   processor.ScheduleJobs(scheduler);   scheduler.Start();   scheduler.Shutdown();     } }}

亦或者這樣


using System.Text; using Quartz;using Quartz.Xml;using Quartz.Impl;using Quartz.Simpl;using System.Threading;using Common.Logging;using System.IO;namespace Demo{ class Program {  static void Main(string[] args)  {       XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper());   ISchedulerFactory sf = new StdSchedulerFactory();   IScheduler scheduler = sf.GetScheduler();      processor.ProcessFileAndScheduleJobs("~/quartz.xml",scheduler);      scheduler.Start();   scheduler.Shutdown();     } }}

目前根據源碼分析大致就這幾種配置方式,很靈活可以任意組合。 關於quartz的使用源碼很詳細,並且園子量有大量的學習文章。

記住quartz的配置讀取方式首先app.config/web.config ---->quartz.config/Quartz.quartz.config ---->quartz_jobs.xml .

通過代碼方式我們可以改變quartz_jobs.xml 的指向即自己新命名的xml檔案

(預設的quartz_jobs.xml是在XMLSchedulingDataProcessor.QuartzXmlFileName = "quartz_jobs.xml"被指定的)

方式一,通過quartz節點/quartz.config指向指定的jobs.xml。

方式二,通過XMLSchedulingDataProcessor 載入指定的jobs.xml

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.