How to Write Quartz JobListener?

In my previous posts I have explained about writing simple quartz scheduler and how to list jobs. This tutorial explains how to write a listener for the scheduler. In certain scenarios, we have to execute few lines of code or log messages before and after the batch process. The listeners are very useful for achieving those goals. In quartz, JobListener interface provides jobToBeExecuted and jobWasExecuted as the callback methods for before and after every job is executed. These methods takes the parameter of JobExecutionContext, with this you can access the current Job details and print them. For the complete setup of the quartz scheduler, please refer my previous tutorial. If you have any questions, please write it in the comments section.

1. Create a Job


import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class FirstJob implements Job{

	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		System.out.println("This is my first quartz job!!");


2. Create Quartz Job Listener


import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;

public class FirstJobListener implements JobListener{

	public String getName() {
		return "FirstJobListener";

	public void jobToBeExecuted(JobExecutionContext context) {
		System.out.println("jobToBeExecuted : " + context.getJobDetail().getKey().toString());

	public void jobWasExecuted(JobExecutionContext context,
			JobExecutionException arg1) {
		System.out.println("jobWasExecuted : " + context.getJobDetail().getKey().toString());

	public void jobExecutionVetoed(JobExecutionContext context) {
		System.out.println("jobExecutionVetoed : " + context.getJobDetail().getKey().toString());


3. Add Quartz Job Listener to Scheduler


import java.util.Date;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.impl.JobDetailImpl;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.triggers.SimpleTriggerImpl;

public class QuartzExample {
	public static void main(String args[]) throws SchedulerException{
		//Creating scheduler factory and scheduler
		SchedulerFactory factory = new StdSchedulerFactory();
		Scheduler scheduler = factory.getScheduler();

		//Creating Job and link to our Job class
		JobDetailImpl jobDetail = new JobDetailImpl();
		jobDetail.setName("First Job");

		//Creating schedule time with trigger
		SimpleTriggerImpl simpleTrigger = new SimpleTriggerImpl();
		simpleTrigger.setStartTime(new Date(System.currentTimeMillis() + 1000));

		//Start scheduler

		//Adding the listener
		scheduler.getListenerManager().addJobListener(new FirstJobListener());

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!