CodesJava

Easy learning with example program codes

Quartz 2.1.5 hello world example using CronTrigger

Example Explanation:

1. Create a job by implementing Job interface.
2. Perform your business logic in the execute method.
3. Create a class for executing quartz job.
4. Get a JobDetail object from JobBuilder and set job detail like name and job class.
5. Create Trigger object from TriggerBuilder and set the scheduler timing and other details.
6. Get Scheduler object from StdSchedulerFactory.
7. Use Scheduler object to connect quartz job and quartz trigger together and execute the job.

Example:

CronTriggerTest.java

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
 
/**
 * This class is used for executing quartz job 
 * using CronTrigger(Quartz 2.1.5).
 * @author codesjava
 */
public class CronTriggerTest {
	public static void main(String args[]){
    	try{
    		//Set job details.
    		JobDetail job = JobBuilder.newJob(HelloJob.class)
    			.withIdentity("helloJob", "group1").build();
 
        	//Set the scheduler timings.
    		Trigger trigger = TriggerBuilder.newTrigger()
    			.withIdentity("cronTrigger", "group1")
    			.withSchedule(CronScheduleBuilder
    			    .cronSchedule("0/10 * * * * ?")).build();
 
        	//Execute the job.
    		Scheduler scheduler = 
    				new StdSchedulerFactory().getScheduler();
        	scheduler.start();
        	scheduler.scheduleJob(job, trigger);
    	}catch(Exception e){
    		e.printStackTrace();
    	}    	
    }
}

HelloJob.java

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
 
/**
 * This class defines a quartz job.
 * @author codesjava
 */
public class HelloJob implements Job{
	public void execute(JobExecutionContext context)
			throws JobExecutionException {	 
		System.out.println("Hello World.");		 
	}
}

Output:

Hello World.
Hello World.
Hello World.
Hello World.
Hello World.
...

Download this example.
 
Next Topic: Quartz 2 JobListener example.
Previous Topic: Quartz 2.1.5 example using SimpleTrigger with example.

 

Please follow and like us:
error








Copyright © 2019 CodesJava DMCA.com Protection Status