Friday, 25 March 2016

What is Quartz scheduler and how to use it ?



Quartz is a powerful and advance scheduler framework used to schedule a job to run at a specified date and time.


1. Download Quartz

Dependencies : quartz 1.6.3, commons-collections 3.2.1, org.apache.commons.logging 1.1.1


2. Quartz Job
  • Defines what you want to run ?
public class MyJob implements Job {
    public void execute(JobExecutionContext context) throws JobExecutionException { 
        System.out.println("Hello Quartz!");    
    } 
}


3. Quartz Trigger
  • Defined when the Quartz will run your above Quartz’s job ?
  • 2 types of Quartz triggers : Simple and Cron triggers

a. SimpleTrigger : allows to set start time, end time, repeat count, repeat interval
SimpleTrigger trigger = new SimpleTrigger();
trigger.setName("myTriggerName");
trigger.setStartTime(new Date(System.currentTimeMillis() + 1000));
trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
trigger.setRepeatInterval(30000);   // Run every 30 seconds

b. CronTrigger : allows Linux CRON expression to specify the dates and times for the job
CronTrigger trigger = new CronTrigger();
trigger.setName("myTriggerName");
trigger.setCronExpression("0/30 * * * * ?");  // Run every 30 seconds


4. Scheduler (linking Job with Trigger)

Scheduler class links both “Job” and “Trigger” together and execute it.
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(job, trigger);

No comments:

Post a Comment

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