Quartz Scheduler Example
In this example we are going to see and use an example for quartz scheduler.
Quartz is a richly featured, open source job scheduling library that can be integrated with virtually any Java application.
We are going to see some quartz scheduler capabilities in this example.
For this example we use the following technologies:
- MAC OSX
- Eclipse Mars.1
- Maven3
- JDK 1.8.0_65 64bits
- Quartz 2.2.1
1. Introduction
Quartz scheduler can help you to add task/jobs inside your java application and run it at a concrete date/time. This kind of tasks are usefull in several situations, almost every kind of real systems have at least one requirement for implement this kind of tasks.
Quartz can be used with some application servers like jboss, weblogic, ibm websphere, etc… and can be used in standalone mode too (console application).
We are going to see and use an example for quartz, in order to do that, we are going to create an empty maven java project, packaging it as a jar file.
2. Example project
In order to make and use an example of quartz scheduler, you will create a maven java project and it will be packaged as a jar file.
You can see the project structure below:
The pom file will add the quartz dependency in order to use it in our code, you can see the pom.xml file below:
pom xml file:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javacodegeeks.examples</groupId> <artifactId>quartz-scheduler-example</artifactId> <version>1.0.0-SNAPSHOT</version> <name>Quartz Scheduler :: example</name> <url>http://maven.apache.org</url> <properties> <quartz.version>2.2.1</quartz.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>${quartz.version}</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz-jobs</artifactId> <version>${quartz.version}</version> </dependency> </dependencies> </project>
The project is declaring quartz
and quartz-job
dependencies, you will need both of them in order to use quartz features inside our projects.
3. Quartz elements
Quartz has three basic elements
- Task/Job: This component is the task itself, it means, the business logic of the operation you want to do. Inside this component you will code the functionality of your desired work.
- Listener: This is a framework component, following a listener pattern the quartz framework will call to this component, giving you the chance to run code in some situations like when the job is started, when the job is finished or when the job is vetoed (banned).
- Trigger: This component can make relationships between jobs and listener and can define a cron pattern to execute the job when that pattern is accomplished
Althought quartz has more features, with those ones you can easily create a task that will be triggered every time the cron pattern is accomplished.
Let´s see all those components in details.
4. Job task
The job task represents the work to do, is the business logic of your process. Here you must indicate all the operations you want to do, like read data from a database, call to a web service, connect to a LDAP Server, or whatever you want.
In order to declare a Quartz job you have to implement the org.quartz.Job
interface. In this example the job will print a Hello world. You can see the job class below:
job class:
package com.javacodegeeks; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class HelloJcgJob implements Job { public void execute(JobExecutionContext context) throws JobExecutionException { System.out.println("Hello Java Code Geeks World!"); } }
As you can see, the HelloJcgJob
class implements the Job interface, and overrides the execute
method, inside of it, we define the job work.
5. Job listener
The job listener represents a way to do some stuff in some job lifecycle events. The quartz framework will invoke this job listener following a listener or adapter pattern. In order to implement a job listener you have to implement the org.quartz.JobListener
interface.
You don´t have to associate a job listener with a job in the job listener definition, you will do that association later.
You can see the job listener of the example below:
job listener class:
package com.javacodegeeks; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.JobListener; public class HelloJcgJobListener implements JobListener { public String getName() { return "HelloJcgJobListener"; } public void jobToBeExecuted(JobExecutionContext context) { final String jobName = context.getJobDetail().getKey().toString(); System.out.println("jobToBeExecuted: " + jobName + " is starting..."); } public void jobExecutionVetoed(JobExecutionContext context) { System.out.println("jobExecutionVetoed"); } public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) { System.out.println("jobWasExecuted"); final 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()); } } }
As you can see, the HelloJcgJobListener
implements the JobListener
interface and override four methods:
- getName: Retrieves the job listener name as a string.
- jobToBeExecuted: Quartz will invoke this method when the job is going to be executed.
- jobExecutionVetoed: Quartz will invoke this method when the job execution was banned from the trigger.
- jobWasExecuted: Quartz will invoke this method when the job was executed.
You can do some stuff in those events in order to control the job execution as you wish/need.
6. Trigger
The trigger element represents the association between job and jobListener. It will be responsible for create the job, create the joblistener, create a trigger event (based on a cron time for example) and throught the quartz scheduler create the relationship between trigger and job and the relationship between job and joblistener.
You don´t have to implement or inherit any interface or class in order to define a trigger.
You can see the example trigger below:
trigger:
package com.javacodegeeks; 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; public class HelloJcgCronTrigger { public static void main(String[] args) throws Exception { final JobKey jobKey = new JobKey("HelloJcgName", "group1"); final JobDetail job = JobBuilder.newJob(HelloJcgJob.class).withIdentity(jobKey).build(); final Trigger trigger = TriggerBuilder.newTrigger().withIdentity("HelloJcgTriggerName", "group1") .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?")).build(); final Scheduler scheduler = new StdSchedulerFactory().getScheduler(); // Listener attached to jobKey scheduler.getListenerManager().addJobListener(new HelloJcgJobListener(), KeyMatcher.keyEquals(jobKey)); scheduler.start(); scheduler.scheduleJob(job, trigger); } }
7. Conclusion
As we have seen, the quartz scheduler allows you to easily define a job that can be executed many times, and in a variety of ways throught the trigger element. You can use quartz with some of the most relevant JEE frameworks like spring, struts2, etc…
8. Download the Source Code
This was an example about Quartz Scheduler.
You can download the full source code of this example here: quartz scheduler example