Java Quartz Scheduler vs Java Timer Example
1.Introduction
This example builds two java scheduler applications: one utilizes Quartz scheduler and the other uses java built-in Timer library.
Quartz – an open source library, enables enterprise to schedule a job/task at a specific date and time. It provides operations to scheduling/unscheduling jobs, starting/stopping/pausing the scheduler.
JDK built-in Timer library enables an application to run the task in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals. It provides cancel and purge methods to terminate the timer and remove all cancelled tasks from this timer’s queue.
2. The Business Task
The business task is a task that business requires to run according to the schedule. It can be scheduled via Quartz scheduler or JDK Timer library, so create it outside the scheduler package. For demonstration purpose, it prints out the current thread name.
MyTask
package jcg.demo.mywork; /** * This class performs the task based the business requirements * * @author Mary.Zheng * */ public class MyTask { /** * It should handle any runtime exception if the application should continue * when encounters a exception, otherwise the application will stop */ public void perform() { System.out.println("\tMyTask performed by thread: " + Thread.currentThread().getName()); } }
3. Quartz Scheduler Example
This example demonstrates how to create a scheduler application with Quartz. This example will fire off a simple job that invokes business related task every minute. The program will perform the following actions:
- Start up the Quartz Scheduler
- Schedule a simple job to run every minute
3.1 Quartz dependency
Add Quartz dependency to maven pom.xml:
pom.xml
<dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.2.1</version> </dependency>
3.2 Quartz job
Create a class which implements org.quartz.Job
interface
QuartzJob
package jcg.demo.scheduler.quartz2; import java.time.LocalDateTime; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import jcg.demo.mywork.MyTask; /** * This class implements Quartz Job interface, anything you wish to be executed * by the Quartz Scheduler should be here. It should invokes business class to * perform task. * * @author Mary.Zheng * */ public class QuartzJob implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { LocalDateTime localTime = LocalDateTime.now(); System.out.println("Run QuartzJob at " + localTime.toString()); MyTask mytask = new MyTask(); mytask.perform(); } }
- line 19: Create
QuartzJob
class which implementsorg.quartz.Job
- line 21 – 28: Override the
execute
method to includeMyTask
created at step 2. This is the connection point to tie the business task to Quartz Job library
3.3 Quartz scheduler application
Quartz supports several scheduler trigger. The example below demonstrates how to schedule a job to run the task every minute. It includes five steps as below:
- Initialize a scheduler instance from Quartz via
StdSchedulerFactory()
- Start the scheduler instance with Quartz API
start()
- Create a scheduler trigger from the Quartz
TriggerBuilder
with theSimpleScheduleBuilder
with 1 minute intervals - Build a
JobDetail
instance from QuartzJobBuilder
for theQuartzJob
created at step 3.2 - Schedule a job with the
someJobDetail
andtrigger
created at above two steps
QuartzSchedulerApp
package jcg.demo.scheduler.quartz2; import org.quartz.CronScheduleBuilder; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SimpleScheduleBuilder; import org.quartz.Trigger; import org.quartz.TriggerBuilder; import org.quartz.impl.StdSchedulerFactory; /** * This application schedule a job to run every minute * * @author Mary.Zheng * */ public class QuartzSchedulerApp { private static final String TRIGGER_NAME = "MyTriggerName"; private static final String GROUP = "simple_Group"; private static final String JOB_NAME = "someJob"; private static Scheduler scheduler; public static void main(String[] args) throws Exception { System.out.println(" QuartzSchedulerApp main thread: " + Thread.currentThread().getName()); scheduler = new StdSchedulerFactory().getScheduler(); scheduler.start(); Trigger trigger = buildSimpleSchedulerTrigger(); // buildCronSchedulerTrigger();// for cron job trigger scheduleJob(trigger); } private static void scheduleJob(Trigger trigger) throws Exception { JobDetail someJobDetail = JobBuilder.newJob(QuartzJob.class).withIdentity(JOB_NAME, GROUP).build(); scheduler.scheduleJob(someJobDetail, trigger); } private static Trigger buildSimpleSchedulerTrigger() { int INTERVAL_SECONDS = 60; Trigger trigger = TriggerBuilder.newTrigger().withIdentity(TRIGGER_NAME, GROUP) .withSchedule( SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(INTERVAL_SECONDS).repeatForever()) .build(); return trigger; } private static Trigger buildCronSchedulerTrigger() { String CRON_EXPRESSION = "0 * * * * ?"; Trigger trigger = TriggerBuilder.newTrigger().withIdentity(TRIGGER_NAME, GROUP) .withSchedule(CronScheduleBuilder.cronSchedule(CRON_EXPRESSION)).build(); return trigger; } }
- line 28: Initialize a
scheduler
via theorg.quartz.impl.StdSchedulerFactory
- line 29: Start the
scheduler
instance - line 31: Build a simple scheduler
trigger
based on the time intervals - line 33: Call private
schedulerJob
method withtrigger
(created at line 31) - line 39: Build a
JobDetail
instance fromorg.quartz.JobBuilder
. This is the connection point which connects the Quartz Job to theQuartzJob
created at step 3.2 - line 41: Invoke the scheduler’s
scheduleJob
method. This is another connection point which connects the Quartzscheduler
(created at line 28) to thesomeJobDetail
(created at line 41) and thetrigger
(created at line 31) all together - line 49-52: Build a scheduler
trigger
fromorg.quartz.TriggerBuilder
based onSimpleScheduleBuilder
withIntervalInSeconds()
to run at every 60 seconds - line 58-59: Build a scheduler
trigger
fromorg.quartz.TriggerBuilder
based onCronSchedulBuilder
with Cron expression to run every minute at 0 second
3.4 Quartz scheduler execution
Run the Quartz scheduler application
Output
QuartzSchedulerApp main thread: main Run QuartzJob at 2017-11-20T16:13:33.811 MyTask performed by thread: DefaultQuartzScheduler_Worker-1 Run QuartzJob at 2017-11-20T16:14:33.773 MyTask performed by thread: DefaultQuartzScheduler_Worker-2 Run QuartzJob at 2017-11-20T16:15:33.774 MyTask performed by thread: DefaultQuartzScheduler_Worker-3
As you see, the job repeatedly runs every minute with different thread.
4. JDK Timer Example
This example demonstrates how to create a java application with JDK Timer library. This example will fire off a simple job that invokes business related task every minute. It only needs two steps to schedule a job.
4.1 JDK Timer task
Create a class which extends from the java.util.TimerTask
TimerJob
package jcg.demo.scheduler.jdktimer; import java.time.LocalDateTime; import java.util.TimerTask; import jcg.demo.mywork.MyTask; /** * This class extends from JDK TimerTask, anything you wish to be executed by * the Timer should be here it should invokes business class to perform task. * * @author Mary.Zheng * */ public class TimerJob extends TimerTask { @Override public void run() { LocalDateTime localTime = LocalDateTime.now(); System.out.println("Run TimerJob at " + localTime.toString()); MyTask task = new MyTask(); task.perform(); } }
- line 15: we create
TimerJob
extends fromjava.util.TimerTask
- line 18-25: we override the
run
method which includes theMyTask
created at step 2. It’s the connection point to tie theTimerJob
to the business task
4.2 JDK Timer application
JDK Timer has six build-in schedule methods. The example below demonstrates how to schedule a timer to run the task every minute after 1 second delay from the beginning.
TimerApp
package jcg.demo.scheduler.jdktimer; import java.util.Timer; import java.util.TimerTask; /** * This application schedule a job to run every minute after 1 second delay. * * @author Mary.Zheng * */ public class TimerApp { private static final int PERIOD_MS = 60000; private static final int DELAY_MS = 1000; public static void main(String[] args) { System.out.println(" TimerSchedulerApp main thread: " + Thread.currentThread().getName()); TimerTask task = new TimerJob(); Timer timer = new Timer(); timer.schedule(task, DELAY_MS, PERIOD_MS); } }
- line 19: we create new
TimerJob
instance created at step 4.1 - line 21: we create new
java.util.Timer
instance - line 22: we invoke the
timer
instance’sschedule
method with theTimerTask
(created at line 19) with 1 second delay and 60 seconds intervals
4.3 JDK Timer execution
Run the JDK Timer application
Output
TimerApp main thread: main Run TimerJob at 2017-11-20T16:19:02.426 MyTask performed by thread: Timer-0 Run TimerJob at 2017-11-20T16:20:02.353 MyTask performed by thread: Timer-0 Run TimerJob at 2017-11-20T16:21:02.354 MyTask performed by thread: Timer-0 Run TimerJob at 2017-11-20T16:22:02.354 MyTask performed by thread: Timer-0 Run TimerJob at 2017-11-20T16:23:02.355 MyTask performed by thread: Timer-0
As you see, the job repeatedly runs every minute with same thread. It’s not ideal for an application which has lots of scheduled jobs.
5. Comparison
As you can see via the demo projects, here are the pros and cons for each of them. The developer should weigh the options to find the option which best suits the business’s needs.
5.1 Quartz Scheduler
Pros:
- has several built-in triggers which most businesses need
- can be extended to meet more complex schedule requirement
- support concurrent threads
Cons:
- not easy to use
5.2 JDK Timer
Pros:
- very easy to use
- has six build-in schedule methods to allow job executed one time, or repeatedly with fixed rate, or with interval delay, etc
Cons:
- cannot schedule with Cron job expression
- cannot extend for other schedule options
6. Conclusion
Quartz scheduler is suited for an enterprise scheduler application. JDK timer is suited for a simple scheduler job. There are other scheduler libraries available as well. A developer should weigh the options to find the best way to satisfy the business’s requirements.
7. Download the Source Code
This example builds two java scheduler applications: one utilizes Quartz scheduler and the other uses java built-in Timer library.
You can download the full source code of this example here: Java Quartz Scheduler vs Java Timer Example
Thank you for clear explanation and examples !
Thanks