Java Quartz Asynchronous Example
In this article, we will show an example of the Java Quartz Asynchronous. Quartz is a richly featured, open-source job scheduling library that can be integrated with any Java application.
1. Introduction
Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components that may execute virtually anything we may program them to do.
Quartz can run embedded within another free-standing application. It can be instantiated within an application server (or servlet container), and participate in XA transactions. It can run as a stand-alone program (within its own Java Virtual Machine), to be used via RMI
2. Job Execution
Jobs can be any Java class that implements the simple interface, leaving infinite possibilities for the work your Jobs can perform. Job
class instances can be instantiated by Quartz, or by your application’s framework.
When a Trigger
occurs, the scheduler notifies zero or more Java objects implementing the JobListener
and TriggerListener
interfaces (listeners can be simple Java objects, or EJBs, or JMS publishers, etc.). These listeners are also notified after the Job
has executed.
As Jobs are completed, they return a JobCompletionCode
which informs the scheduler of success or failure. They can also instruct the scheduler of any actions it should take based on the success/fail code – such as immediate re-execution of the Job.
3. Simple Job
In this section, we will see an example of running a simple job. We will schedule a job to be run after 5 seconds then we will wait for its execution. Let’s first see how the Job looks like. Our job will simply implement the org.quartz.Job
interface and will override the execute
method.
ExampleJob.java
package org.javacodegeeks; import org.quartz.Job; import org.quartz.JobExecutionContext; import java.time.LocalDateTime; public class ExampleJob implements Job { public void execute(JobExecutionContext jobExecutionContext) { System.out.println("Job executed at: " + LocalDateTime.now().toString()); } }
Now we will see how to schedule and trigger this job. First, we need to get the scheduler instance.
SchedulerFactory schedulerFactory = new StdSchedulerFactory(); Scheduler scheduler = schedulerFactory.getScheduler();
A Scheduler
maintains a registry of JobDetails
and Triggers
. Once registered, the Scheduler
is responsible for executing Jobs
when their associated Triggers
fire (when their scheduled time arrives). Scheduler
instances are produced by a SchedulerFactory
. A scheduler that has already been created/initialized can be found and used through the same factory that produced it. After a Scheduler
has been created, it is in “stand-by” mode and must have its start()
method called before it will fire any Jobs.
Now we will create the job and will tie it to the ExampleJob class:
JobDetail job = newJob(ExampleJob.class).withIdentity("MyJobName", "MyJobGroup").build();
Quartz does not store an actual instance of a Job
class, but instead allows you to define an instance of one, through the use of a JobDetail
. Jobs
have a name and group associated with them, which should uniquely identify them within a single Scheduler
. Now trigger the job to run after 5 minutes:
Trigger trigger = newTrigger().withIdentity("MyTriggerName", "MyTriggerGroup").startAt(date).build();
Triggers
are the ‘mechanism’ by which Jobs
are scheduled. Many Triggers
can point to the same Job, but a single Trigger
can only point to one Job. Tell quartz to scheduler the job using out trigger:
scheduler.scheduleJob(job, trigger);
Now start the scheduler:
scheduler.start();
QuartzExample.java
package org.javacodegeeks; import org.quartz.*; import org.quartz.impl.StdSchedulerFactory; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; import static org.quartz.JobBuilder.newJob; import static org.quartz.TriggerBuilder.newTrigger; public class QuartzExample { public static void main(String[] args) { QuartzExample quartzExample = new QuartzExample(); quartzExample.run(); } private void run() { // First we must get a reference to a scheduler SchedulerFactory schedulerFactory = new StdSchedulerFactory(); try { Scheduler scheduler = schedulerFactory.getScheduler(); // define the job and tie it to our HelloJob class JobDetail job = newJob(ExampleJob.class).withIdentity("MyJobName", "MyJobGroup").build(); // Trigger the job to run after 5 minutes Date date = Date.from(LocalDateTime.now().plusSeconds(5).atZone(ZoneId.systemDefault()).toInstant()); Trigger trigger = newTrigger().withIdentity("MyTriggerName", "MyTriggerGroup").startAt(date).build(); // Tell quartz to schedule the job using our trigger scheduler.scheduleJob(job, trigger); System.out.println(job.getKey() + " will run at: "+ date); // Start up the scheduler (nothing can actually run until the scheduler has been started) scheduler.start(); // wait long enough so that the scheduler as an opportunity to run the job! System.out.println("Waiting for 10 seconds"); try { // wait 65 seconds to show job Thread.sleep(10*1000); } catch (Exception e) { } // Shutdown the scheduler scheduler.shutdown(true); } catch (SchedulerException e) { e.printStackTrace(); } } }
When you will run the job you will see output like:
MyJobGroup.MyJobName will run at: Sun Aug 02 22:19:08 BST 2020 Waiting for 10 seconds Job executed at: 2020-08-02T22:19:08.319
4. Cron Job
In the previous section, we saw how to create a simple job and ow schedule it. In this, we will see how to create a cron job using cron expression. The process of creating the job remains the same but instead of creating a general Trigger we will create a CronTrigger:
CronTrigger trigger = newTrigger().withIdentity("MyFirstTrigger", "MyFirstGroup").withSchedule(cronSchedule("0/3 * * * * ?")).build();
The cron expression (“0/3 * * * * ?”) will make the job run after every 3 seconds. The rest of the method of starting the scheduler remains the same.
CronExample.java
package org.javacodegeeks.cron; import org.javacodegeeks.ExampleJob; import org.quartz.*; import org.quartz.impl.StdSchedulerFactory; import java.util.Date; import static org.quartz.CronScheduleBuilder.cronSchedule; import static org.quartz.JobBuilder.newJob; import static org.quartz.TriggerBuilder.newTrigger; public class CronExample { public static void main(String[] args) { CronExample cronExample = new CronExample(); cronExample.run(); } private void run() { SchedulerFactory schedulerFactory = new StdSchedulerFactory(); try { Scheduler scheduler = schedulerFactory.getScheduler(); // jobs can be scheduled before scheduler.start() has been called // MyFirstJob will run every 3 seconds JobDetail job = newJob(ExampleJob.class).withIdentity("MyFirstJob", "MyFirstGroup").build(); CronTrigger trigger = newTrigger().withIdentity("MyFirstTrigger", "MyFirstGroup").withSchedule(cronSchedule("0/3 * * * * ?")).build(); Date date = scheduler.scheduleJob(job, trigger); System.out.println(String.format("%s has been scheduled to run at: %s and is repeated based on the cron expression: %s", job.getKey(), date, trigger.getCronExpression())); scheduler.start(); try { Thread.sleep(15 * 1000); // executing... } catch (Exception e) { // } scheduler.shutdown(true); } catch (SchedulerException e) { e.printStackTrace(); } } }
5. Summary
In this article, we discussed how to schedule a job using Quartz. We discussed the creation of a simple job than a cron job.
6. Download the source code
You can download the full source code of this example here: Java Quartz Asynchronous Example