Home  >  Quartz

Quartz 2 Scheduler Example with Trigger and CronTrigger using Job, SchedulerFactory, JobDetail, CronScheduleBuilder, JobBuilder, TriggerBuilder, JobKey and JobExecutionContext

By Arvind Rai, May 21, 2015
Quartz is an open source job scheduling library which can be used to create simple or complex schedules in java. Quartz provides easy steps to schedule our job. It provides a Job interface using which we have to create our job that will be scheduled. Now instantiate Scheduler using SchedulerFactory. Create a JobDetail and Trigger that will be registered to Scheduler and finally start it. Trigger is the base interface for all triggers. One such implementation is CronTrigger which uses cron- expression with the help of CronScheduleBuilder. Here in this page we will describe each and every term for Quartz scheduler getting started. We will provide two examples using Trigger and CronTrigger.

Job, JobExecutionContext and JobKey

org.quartz.Job is an interface which is implemented by a class to define a job which will run by quartz scheduler. The class must have a no argument public constructor. Job interface has a method
execute(JobExecutionContext context)
 
which needs to be implemented by the class. We need to put our task here in this method which is supposed to run by quartz scheduler. JobExecutionContext is the argument of this method. This class provides the information given to JobDetail. One such information is JobKey which uniquely identifies a JobDetail. We can use these classes as below.
JobDetail jobDetail = context.getJobDetail();
JobKey key = jobDetail.getKey(); 



SchedulerFactory and Scheduler

To start our job by scheduler we need the instance of Scheduler which is obtained by SchedulerFactory.
SchedulerFactory schfa = new StdSchedulerFactory();
Scheduler sch = schfa.getScheduler();  
We need to register JobDetail and Trigger instances to Schedulerusing its scheduleJob() method.
sch.scheduleJob(jobdetail, trigger)
 
Finally we need to start the scheduler and after some time we can shut down if needed.
sch.start();
Thread.sleep(80L * 1000L);
sch.shutdown(true);  

JobDetail and JobBuilder

org.quartz.JobDetail registers the Job. We have to provide a unique identity to it using job name and group name within a single scheduler. In this way each and every instances of JobDetail are created uniquely. JobBuilder creates JobDetail.
JobDetail jobdetail = JobBuilder.newJob(MyJob.class)
    .withIdentity("myjob1", "mygroup1").build(); 

Trigger and TriggerBuilder

org.quartz.Trigger is the base interface for all triggers. This provides the common methods to all implemented triggers. To instantiate Trigger, we need to use TriggerBuilder.
Trigger trigger = TriggerBuilder.newTrigger().withIdentity("mytrigger1", "mygroup1")
    .startAt(new Date(Calendar.getInstance().getTimeInMillis()+ 5000)).build(); 
Many triggers can point to same job, but a single trigger can point only one job. It means we can explain in way that the relationship between trigger and job is many-to-one but not one-to-many.

CronTrigger and CronScheduleBuilder

org.quartz.CronTrigger helps to start a job using Unix cron- like schedule definitions. CronTrigger schedules a repetitive job for a given cron-expression. To do this we need a ScheduleBuilder. There are many implementations of ScheduleBuilder and one of which is CronScheduleBuilder which accepts cron-expression as an input.
CronTrigger crontrigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "crongroup1")
    .withSchedule(craeteSchedule("0 0/1 * 1/1 * ? *")).build(); 
Here 0 0/1 * 1/1 * ? * is a cron- expression that executes job after every minute.

Gradle to Resolve Quartz 2 JAR Dependencies

Find the gradle file to resolve JAR dependencies of Quartz.
build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
archivesBaseName = 'concretepage'
version = '1' 
repositories {
    mavenLocal()
    mavenCentral()
}
dependencies {
	compile 'org.quartz-scheduler:quartz:2.2.1'
} 
jar {
	manifest {
		attributes 'Main-Class': 'com.concretepage.TriggerQuartzTest'
	}
} 

Create a Job

Create a simple Job.
MyJob.java
package com.concretepage.job;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
public class MyJob implements Job {
	@Override
	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		JobDetail jobDetail = context.getJobDetail();
		JobKey key = jobDetail.getKey();
		System.out.println("For Job key:"+ key +", Current Date:"+ new Date());
	}
} 

Quartz 2 Scheduler Example with Trigger

Find first example to schedule a job. Here the job will be schedules only one time.
TriggerQuartzTest.java
package com.concretepage;
import java.util.Calendar;
import java.util.Date;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import com.concretepage.job.MyJob;
public class TriggerQuartzTest {
	public static void main(String[] args) throws SchedulerException, InterruptedException {
		SchedulerFactory schfa = new StdSchedulerFactory();
		Scheduler sch = schfa.getScheduler();
		JobDetail jobdetail = JobBuilder.newJob(MyJob.class)
		    .withIdentity("myjob1", "mygroup1").build();
		//Executes only one time
		Trigger trigger = TriggerBuilder.newTrigger().withIdentity("mytrigger1", "mygroup1")
		    .startAt(new Date(Calendar.getInstance().getTimeInMillis()+ 5000)).build();
		sch.scheduleJob(jobdetail, trigger);
		sch.start();
		Thread.sleep(70L * 1000L);
		sch.shutdown(true);
	}
} 
Find the output.
For Job key:mygroup1.myjob1, Current Date:Thu May 21 14:37:10 IST 2015
 

Quartz 2 Scheduler Example with CronTrigger

In this example, we are using cron-expression to schedule the job.
CronTriggerQuartzTest.java
package com.concretepage;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.ScheduleBuilder;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import com.concretepage.job.MyJob;
public class CronTriggerQuartzTest {
	public static void main(String[] args) throws SchedulerException, InterruptedException {
		SchedulerFactory schfa = new StdSchedulerFactory();
		Scheduler sch = schfa.getScheduler();
		JobDetail jobdetail = JobBuilder.newJob(MyJob.class)
			    .withIdentity("cronjob1", "crongroup1").build();
		//Executes after every minute 0 0/1 * 1/1 * ? *
		CronTrigger crontrigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "crongroup1")
			    .withSchedule(craeteSchedule("0 0/1 * 1/1 * ? *")).build();
		sch.scheduleJob(jobdetail, crontrigger);
		jobdetail = JobBuilder.newJob(MyJob.class)
			    .withIdentity("cronjob2", "crongroup1").build();
		//Executes after every 2 minute 0 0/2 * 1/1 * ? *
		crontrigger = TriggerBuilder.newTrigger().withIdentity("trigger2", "crongroup1")
			    .withSchedule(craeteSchedule("0 0/2 * 1/1 * ? *")).build();
		sch.scheduleJob(jobdetail, crontrigger);
		sch.start();
		Thread.sleep(100L * 1000L);
		sch.shutdown(true);
	}
	private static ScheduleBuilder craeteSchedule(String cronExpression){
		CronScheduleBuilder builder = CronScheduleBuilder.cronSchedule(cronExpression);
		return builder;
	}
} 
In the example, we are showing job scheduling for two cron-expressions. There can be more than one trigger to schedule a single job. Find the output.
For Job key:crongroup1.cronjob1, Current Date:Thu May 21 14:46:00 IST 2015
For Job key:crongroup1.cronjob2, Current Date:Thu May 21 14:46:00 IST 2015
For Job key:crongroup1.cronjob1, Current Date:Thu May 21 14:47:00 IST 2015 

Download Complete Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us