Friday, 25 March 2016

How to schedule jobs using XML in Quartz ?


Create “quartz.properties” and “quartz-config.xml” and ensure they are located at project classpath.

1. Create 3 Quartz’s jobs

public class Job1 implements Job {
   @Override
   public void execute(JobExecutionContext context) throws JobExecutionException {
      System.out.println("Job 1 is runing");
   }
}

public class Job2 implements Job {
   @Override
   public void execute(JobExecutionContext context) throws JobExecutionException {
      System.out.println("Job 2 is runing");
   }
}


2. Create quartz.properties

org.quartz.scheduler.instanceName = MyScheduler
org.quartz.threadPool.threadCount = 3
org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
org.quartz.plugin.jobInitializer.class =org.quartz.plugins.xml.XMLSchedulingDataProcessorPlugin
org.quartz.plugin.jobInitializer.fileNames = quartz-config.xml
org.quartz.plugin.jobInitializer.failOnFileNotFound = true


3. Create quartz-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<job-scheduling-data
  xmlns="http://www.quartz-scheduler.org/xml/JobSchedulingData"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.quartz-scheduler.org/xml/JobSchedulingData
  <schedule>
    <job>
      <name>Job1</name>
      <group>myGroupy</group>
      <description>This is Job 1</description>
      <job-class>com.shaan.Job1</job-class>
    </job>

    <trigger>
      <cron>
        <name>myTriggerName1</name>
        <job-name>Job1</job-name>
        <job-group>myGroup</job-group>
        <!-- It will run every 5 seconds -->
        <cron-expression>0/5 * * * * ?</cron-expression>
      </cron>
    </trigger>
  </schedule>

  <schedule>
    <job>
      <name>Job2</name>
      <group>myGroup</group>
      <description>This is Job 2</description>
      <job-class>com.shaan.Job2</job-class>
    </job>

    <trigger>
      <cron>
        <name>myTriggerName2</name>
        <job-name>Job2</job-name>
        <job-group>myGroup</job-group>
        <!-- It will run every 5 seconds -->
        <cron-expression>0/5 * * * * ?</cron-expression>
      </cron>
    </trigger>
  </schedule>
</job-scheduling-data>


4. Entry in web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app ...>
  <listener>
    <listener-class> 
      org.quartz.ee.servlet.QuartzInitializerListener 
    </listener-class>
  </listener>
</web-app>

No comments:

Post a Comment

Note: only a member of this blog may post a comment.