Quartz.net通過設定檔來完成作業調度

來源:互聯網
上載者:User

將Quartz.NET整合到 Castle中 例子代碼使用的Quartz.net版本是0.6,Quartz.NET 0.9 發布了 ,最新版本支援通過設定檔來完成背景作業調度,不必手工建立Trigger和Scheduler。將QuartzStartable 改造如下:

using System;
using System.Collections.Generic;
using System.Text;

using Castle.Core;
using Quartz.Impl;
using Quartz;
using Common.Logging;
using System.Threading;
using System.IO;
using Quartz.Xml;
using System.Collections;

namespace QuartzComponent
{
    [Transient]
    public class QuartzStartable : IStartable
    {
        private ISchedulerFactory _schedFactory;
        private JobSchedulingDataProcessor processor;

        private static ILog log = LogManager.GetLogger(typeof(QuartzStartable));

        public QuartzStartable(ISchedulerFactory schedFactory)
        {
            _schedFactory = schedFactory;
            processor = new JobSchedulingDataProcessor(true, true);
        }

        public void Start()
        {
            log.Info("Starting service");
            IScheduler sched = _schedFactory.GetScheduler();

            //log.Info("------- Scheduling Jobs ----------------");

            //// jobs can be scheduled before sched.start() has been called

            //// get a "nice round" time a few seconds in the future...
            //DateTime ts = TriggerUtils.GetNextGivenSecondDate(null, 15);

            //// job1 will only fire once at date/time "ts"
            //JobDetail job = new JobDetail("job1", "group1", typeof(SimpleQuartzJob));
            //SimpleTrigger trigger = new SimpleTrigger("trigger1", "group1");
            //// set its start up time
            //trigger.StartTimeUtc = ts;
            //// set the interval, how often the job should run (10 seconds here)
            //trigger.RepeatInterval = 10000;
            //// set the number of execution of this job, set to 10 times.
            //// It will run 10 time and exhaust.
            //trigger.RepeatCount = 100;

            //// schedule it to run!
            //DateTime ft = sched.ScheduleJob(job, trigger);
            //log.Info(string.Format("{0} will run at: {1} and repeat: {2} times, every {3} seconds",
            //    job.FullName, ft.ToString("r"), trigger.RepeatCount, (trigger.RepeatInterval / 1000)));
            //log.Info("------- Waiting five minutes... ------------");

            //sched.Start();
            Stream s = ReadJobXmlFromEmbeddedResource("MinimalConfiguration.xml");
            processor.ProcessStream(s, null);
            processor.ScheduleJobs(new Hashtable(), sched, false);
            sched.Start();
            try
            {
                // wait five minutes to show jobs
                Thread.Sleep(300 * 1000);
                // executing...
            }
            catch (ThreadInterruptedException)
            {
            }

        }

        private static Stream ReadJobXmlFromEmbeddedResource(string resourceName)
        {
            string fullName = "QuartzComponent." + resourceName;
            return new StreamReader(typeof(QuartzStartable).Assembly.GetManifestResourceStream(fullName)).BaseStream;
        }

        public void Stop()
        {
            log.Info("Stopping service");
            try
            {
                IScheduler scheduler = _schedFactory.GetScheduler();
                scheduler.Shutdown(true);
            }
            catch (SchedulerException se)
            {
                log.Error("Cannot shutdown scheduler.", se);
            }

        }
    }
}
增加一個設定檔MinimalConfiguration.xml,設定為嵌入資源類型。內容如下:

<?xml version="1.0" encoding="UTF-8"?>
<quartz xmlns="http://quartznet.sourceforge.net/JobSchedulingData"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    version="1.0"
    overwrite-existing-jobs="true">
 
  <job>
  <job-detail>
   <name>jobName1</name>
   <group>jobGroup1</group>
   <job-type>QuartzComponent.SimpleQuartzJob, QuartzComponent</job-type>
  </job-detail>
   
  <trigger>
   <simple>
    <name>simpleName</name>
    <group>simpleGroup</group>
    <job-name>jobName1</job-name>
    <job-group>jobGroup1</job-group>
    <start-time>2007-12-09T18:08:50</start-time>
    <repeat-count>100</repeat-count>
    <repeat-interval>3000</repeat-interval>
   </simple>
      </trigger>
   <trigger>
    <cron>
     <name>cronName</name>
     <group>cronGroup</group>
     <job-name>jobName1</job-name>
     <job-group>jobGroup1</job-group>
     <start-time>1982-06-28T18:15:00+02:00</start-time>
     <cron-expression>0/10 * * * * ?</cron-expression>
    </cron>
   </trigger>
 </job>
</quartz>
可以看到,在設定檔中把jobdetail和trigger都作了完整的定義,並組合成一個job。

當然也可以在quartz.properties檔案中設定一個quertz_job.xml檔案,例如:

            // First we must get a reference to a scheduler
            NameValueCollection properties = new NameValueCollection();
            properties["quartz.scheduler.instanceName"] = "XmlConfiguredInstance";
           
            // set thread pool info
            properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
            properties["quartz.threadPool.threadCount"] = "5";
            properties["quartz.threadPool.threadPriority"] = "Normal";

            // job initialization plugin handles our xml reading, without it defaults are used
            properties["quartz.plugin.xml.type"] = "Quartz.Plugin.Xml.JobInitializationPlugin, Quartz";
            properties["quartz.plugin.xml.fileNames"] = "~/quartz_jobs.xml";
            ISchedulerFactory sf = new StdSchedulerFactory(properties);

這樣,在啟動Castle的時候,Quartz.Plugin.Xml.JobInitializationPlugin就會自動讀取quartz.properties這個設定檔,並初始化調度資訊,啟動Scheduler。

一個Job類,一個quartz.properties檔案,一個quertz_job.xml檔案,非常簡單靈活。

下載例子代碼 :QuartzComponentWithXml.zip

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.