basquang™ on clouds

August 6, 2014

[Quartz.NET]: Configure Job in XML using Quartz plug-in XMLSchedulingDataProcessorPlugin

Filed under: Quartz,Quartz.NET — basquang @ 2:57 PM
Tags: ,

You can initialize the scheduler with predefined jobs and triggers using the XMLSchedulingDataProcessorPlugin. This plugin loads XML file(s) to add jobs and schedule them with triggers as the scheduler is initialized, and can optionally periodically scan the file for changes.The XML schema definition can be found here: http://www.quartz-scheduler.org/xml/job_scheduling_data_2_0.xsd

Here are simple steps to use Quartz.NET plugin

  1. Create Console Application
  2. Install Quartz.NET from NuGet
  3. Add logging configuration in App.config as below

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    
      <configSections>
        <sectionGroup name="common">
          <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging"/>
        </sectionGroup>
      </configSections>
    
      <common>
        <logging>
          <factoryAdapter type="Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter, Common.Logging">
            <arg key="showLogName" value="true"/>
            <arg key="showDataTime" value="true"/>
            <arg key="level" value="INFO"/>
            <arg key="dateTimeFormat" value="HH:mm:ss:fff"/>
          </factoryAdapter>
        </logging>
      </common>
      
        <startup> 
            <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
        </startup>
    </configuration>
    

  4. Create a simple job as code below

    namespace Lesson5
    {
        public class SimpleJob : IJob
        {
            private static readonly ILog log = LogManager.GetLogger(typeof(SimpleJob));
    
            /// <summary>
            /// Called by the <see cref="IScheduler" /> when a
            /// <see cref="ITrigger" /> fires that is associated with
            /// the <see cref="IJob" />.
            /// </summary>
            public virtual void Execute(IJobExecutionContext context)
            {
                // This job simply prints out its job name and the
                // date and time that it is running
                JobKey jobKey = context.JobDetail.Key;
                log.InfoFormat("Executing job: {0} executing at {1}", jobKey, DateTime.Now.ToString("r"));
    
    
                if (context.MergedJobDataMap.Count > 0)
                {
                    ICollection<string> keys = context.MergedJobDataMap.Keys;
                    foreach (string key in keys)
                    {
                        String val = context.MergedJobDataMap.GetString(key);
                        log.InfoFormat(" - jobDataMap entry: {0} = {1}", key, val);
                    }
                }
    
                context.Result = "hello";
            }
        }
    }
    

  5. Create a xml file named as quartz_jobs.xml and set Build Action=Content and Copy to Output Directory=Copy always as below

    <?xml version="1.0" encoding="utf-8" ?>
    <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>
          <name>jobName1</name>
          <group>jobGroup1</group>
          <description>jobDesciption1</description>
          <job-type>Lesson5.SimpleJob, Lesson5</job-type>
          <durable>true</durable>
          <recover>false</recover>
          <job-data-map>
            <entry>
              <key>key0</key>
              <value>value0</value>
            </entry>
            <entry>
              <key>key1</key>
              <value>value1</value>
            </entry>
            <entry>
              <key>key2</key>
              <value>value2</value>
            </entry>
          </job-data-map>
        </job>
    
        <trigger>
          <simple>
            <name>simpleName</name>
            <group>simpleGroup</group>
            <description>SimpleTriggerDescription</description>
            <job-name>jobName1</job-name>
            <job-group>jobGroup1</job-group>
            <start-time>1982-06-28T18:15:00.0Z</start-time>
            <end-time>2020-05-04T18:13:51.0Z</end-time>
            <misfire-instruction>SmartPolicy</misfire-instruction>
            <repeat-count>100</repeat-count>
            <repeat-interval>3000</repeat-interval>
          </simple>
        </trigger>
    
      </schedule>
    
    </job-scheduling-data>
    

  6. Loading the job in XML plugin in Program console as code below

    ILog log = LogManager.GetLogger(typeof(Program));
    
    // our properties that enable XML configuration plugin
    // and makes it watch for changes every two minutes (120 seconds)
    var properties = new NameValueCollection();
    properties["quartz.plugin.triggHistory.type"] = "Quartz.Plugin.History.LoggingJobHistoryPlugin";
    
    properties["quartz.plugin.jobInitializer.type"] = "Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin";
    properties["quartz.plugin.jobInitializer.fileNames"] = "quartz_jobs.xml";
    properties["quartz.plugin.jobInitializer.failOnFileNotFound"] = "true";
    properties["quartz.plugin.jobInitializer.scanInterval"] = "120";
    
    // First we must get a reference to a scheduler
    ISchedulerFactory sf = new StdSchedulerFactory(properties);
    IScheduler sched = sf.GetScheduler();
    
    // start the schedule 
    sched.Start();
    
    // wait five minutes to give our jobs a chance to run
    try
    {
    	Thread.Sleep(TimeSpan.FromMinutes(5));
    }
    catch (ThreadInterruptedException)
    {
    }
    
    // shut down the scheduler
    sched.Shutdown(true);      
    

Hope this help!

Advertisements

1 Comment »

  1. I’ve been surfing on-line greater than three hours as
    of late, but I never found any attention-grabbing article like yours.

    It’s beautiful price enough for me. Personally, if all webmasters and bloggers made excellent
    content material as you did, the internet shall be a lot more helpful than ever before.

    Comment by jack — April 21, 2016 @ 4:39 AM | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: