Main Tutorials

Quartz 2 JobListener example

In this tutorial, we will show you how to create a JobListener, to keep track the running jobs status, like when the job is finished.

P.S This example is tested with Quartz 2.1.5

1. Quartz Job

Job, print a simple message, and throw a JobExecutionException for testing.

File : HelloJob.java


package com.mkyong.quartz;

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

public class HelloJob implements Job
{
	public void execute(JobExecutionContext context)
	throws JobExecutionException {
		
		System.out.println("Hello Quartz! 123");	
		
		//Throw exception for testing
		throw new JobExecutionException("Testing Exception");
	}
	
}

2. JobListener

To create a JobListener, just implements the JobListener interface, and override all the interface’s methods.

File : HelloJobListener.java


package com.mkyong.quartz.listener;

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

public class HelloJobListener implements JobListener {

	public static final String LISTENER_NAME = "dummyJobListenerName";

	@Override
	public String getName() {
		return LISTENER_NAME; //must return a name
	}

	// Run this if job is about to be executed.
	@Override
	public void jobToBeExecuted(JobExecutionContext context) {

		String jobName = context.getJobDetail().getKey().toString();
		System.out.println("jobToBeExecuted");
		System.out.println("Job : " + jobName + " is going to start...");

	}

	// No idea when will run this?
	@Override
	public void jobExecutionVetoed(JobExecutionContext context) {
		System.out.println("jobExecutionVetoed");
	}

	//Run this after job has been executed
	@Override
	public void jobWasExecuted(JobExecutionContext context,
			JobExecutionException jobException) {
		System.out.println("jobWasExecuted");

		String jobName = context.getJobDetail().getKey().toString();
		System.out.println("Job : " + jobName + " is finished...");

		if (!jobException.getMessage().equals("")) {
			System.out.println("Exception thrown by: " + jobName
				+ " Exception: " + jobException.getMessage());
		}

	}

}
Note
No idea what is “jobExecutionVetoed” and when will it triggered? Do comment if you know this, thanks.

3. CronTrigger

Example to attach above HelloJobListener to scheduler, and monitor the job’s states.

File : CronTriggerExample.java


package com.mkyong.quartz;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.KeyMatcher;

import com.mkyong.quartz.listener.HelloJobListener;

public class CronTriggerExample {
    public static void main( String[] args ) throws Exception
    {
    	   	
	JobKey jobKey = new JobKey("dummyJobName", "group1");
    	JobDetail job = JobBuilder.newJob(HelloJob.class)
		.withIdentity(jobKey).build();

    	Trigger trigger = TriggerBuilder
		.newTrigger()
		.withIdentity("dummyTriggerName", "group1")
		.withSchedule(
			CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
		.build();
    	
    	Scheduler scheduler = new StdSchedulerFactory().getScheduler();
    	
    	//Listener attached to jobKey
    	scheduler.getListenerManager().addJobListener(
    		new HelloJobListener(), KeyMatcher.keyEquals(jobKey)
    	);
    	
    	//Listener attached to group named "group 1" only.
    	//scheduler.getListenerManager().addJobListener(
    	//	new HelloJobListener(), GroupMatcher.jobGroupEquals("group1")
    	//);

    	scheduler.start();
    	scheduler.scheduleJob(job, trigger);
    
    }
}

Run CronTriggerExample.java, here’s the output.


jobToBeExecuted
Job : group1.dummyJobName is going to start...
Hello Quartz! 123
jobWasExecuted
Job : group1.dummyJobName is started and finished...
Exception thrown by: group1.dummyJobName Exception: Testing Exception

jobToBeExecuted
Job : group1.dummyJobName is going to start...
Hello Quartz! 123
jobWasExecuted
Job : group1.dummyJobName is started and finished...
Exception thrown by: group1.dummyJobName Exception: Testing Exception

Download Source Code

Download it – Quartz2-JobListener-Example.zip (13 KB)

References

  1. Quartz Official Website
  2. Quartz 2 JobListener Documentation
  3. Quartz 2 hello world example

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
8 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Sushant Singh Ahluwalia
7 years ago

Hi logging is working fine. But when i tried to @autowire any service inside the HelloJobListener. I m getting null pointer exception. Why my service is not getting auto wired here ?

Dharita Chokshi
6 years ago

Quartz job by default doesn’t support @Autowire, we need to explicitly add auto wore support. Below link will be helpful.
https://gist.github.com/jelies/5085593

Komal Prasad
2 years ago

Hi,

I have a WAR file deployed on tomcat, which so the scheduling task, I’m using quartz and added the quartz.properties

org.quartz.scheduler.makeSchedulerThreadDaemon=true
org.quartz.threadPool.makeThreadsDaemons=true

Now Issue is Whenever I shutdown the server it gives a warning about the thread.

java – Memory Leak while Stopping Tomcat Server 9 (War File Grails) – Stack Overflow

Question:
How I shutdown the Scheduler, when the user tried to shutdown the tomcat server

Ram
6 years ago

Hi Yong,
Can we refire the job on exception in jobWasExecuted method in JobListener

Kapil Arora
8 years ago

public void jobExecutionVetoed(JobExecutionContext context)
{
System.out.println(“jobExecutionVetoed”);
}

Let’s say we have a job J and trigger T.

We have a method in TriggerListener vetoJobExecution(). This method is executed when the trigger is just fired. So, with this we can thereby control whether to execute or dismiss the job associated with the trigger. If we want to dismiss the job , then we should return true from this method.

Kapil Arora
8 years ago
Reply to  Kapil Arora

As soon as ,we returned from this method, “jobExecutionVetoed()” method inside our joblistener will be executed to intimate that the job execution has been banned(vetoed).

Ethan
10 years ago

If your implementation ever needs to veto a job, then you can attach a TriggerListener to it and by returning true you’ll stop the job’s execute method being called. You could use this if you had an application that needed to be able to stop Jobs on some type of runtime dependency (say you detect a problem with the database that your job uses).

The quartz documentation doesn’t have much to say on it:
http://quartz-scheduler.org/api/2.0.0/org/quartz/JobListener.html
http://quartz-scheduler.org/api/2.0.0/org/quartz/TriggerListener.html

And a Stack overflow post asked something similar to your question as well:
http://stackoverflow.com/a/16609729/1808164

sathesh
11 years ago

Hi Yong ,
After adding Listener to Job , my cron is not running after the first time .
if the listener line is commented, then works fine .. can u pls help with this

Thanks !