What is Quartz?
Quartz is a job scheduling system that can be integrated with, or used along side virtually any other software system. The term “job scheduler” seems to conjure different ideas for different people. As you read this tutorial, you should be able to get a firm idea of what we mean when we use this term, but in short, a job scheduler is a system that is responsible for executing (or notifying) other software components when a pre-determined (scheduled) time arrives.
Quartz is quite flexible, and contains multiple usage paradigms that can be used separately or together, in order to achieve your desired behavior, and enable you to write your code in the manner that seems most ‘natural’ to your project.
Quartz is very light-weight, and requires very little setup/configuration – it can actually be used ‘out-of-the-box’ if your needs are relatively basic.
Quartz is fault-tolerant, and can persist (‘remember’) your scheduled jobs between system restarts.
Although Quartz is extremely useful for simply running certain system processes on given schedules, the full potential of Quartz can be realized when you learn how to use it to drive the flow of your application’s business processes.
Why not just use java.util.Timer?
Since JDK 1.3, Java has “built-in” timer capabilities, through the java.util.Timer and java.util.TimerTask classes – why would someone use Quartz rather than these standard features?
There are many reasons! Here are a few:
- Timers have no persistence mechanism.
- Timers have inflexible scheduling (only able to set start-time & repeat interval, nothing based on dates, time of day, etc.)
- Timers don’t utilize a thread-pool (one thread per timer)
- Timers have no real management schemes – you’d have to write your own mechanism for being able to remember, organize and retrieve your tasks by name, etc.
Download the jar files for Quartz from here.
jar files neede are:
quartz-2.0.2.jar
slfj-log4j12-1.6.1.jar
sl4j-api-1.6.1.jar
log4j-1.2.14.jar
Example with Source code:
DisplayCurrentTime.java
package in.shivasoft.quartz; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class DisplayCurrentTime implements Job { Calendar c; Date d; SimpleDateFormat sdf; public DisplayCurrentTime() {} @Override public void execute(JobExecutionContext context) throws JobExecutionException { c = new GregorianCalendar(); d = c.getTime(); sdf = new SimpleDateFormat("d MMMMM yyyy - HH:mm:ss aaa"); String msg = String.format("Job Name - %s, Current Time - %s", context.getJobDetail().getKey(), sdf.format(d)); System.out.println(msg); } }
Create a class which should be executed by the quartz scheduler. The class must implement the interface “Job“. The Job interface has only one method “execute()“. The logic which should be executed must be written in this method. There must be the default constructor in class, as scheduler will create the object of that class at runtime.
SimpleQuartzDemo.java
package in.shivasoft.quartz; import java.text.ParseException; import java.util.Date; import org.quartz.CronScheduleBuilder; import org.quartz.CronTrigger; import org.quartz.DateBuilder; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SchedulerFactory; import org.quartz.SimpleScheduleBuilder; import org.quartz.SimpleTrigger; import org.quartz.Trigger; import org.quartz.TriggerBuilder; import org.quartz.impl.StdSchedulerFactory; public class SimpleQuartzDemo { /** * @param args */ public static void main(String[] args) { SimpleQuartzDemo obj = new SimpleQuartzDemo(); obj.runDemo(); } public void runDemo() { try { // First we must get a reference to a scheduler SchedulerFactory sf = new StdSchedulerFactory(); Scheduler sched = sf.getScheduler(); /** * Job 1 using Trigger */ JobDetail job1 = JobBuilder.newJob(DisplayCurrentTime.class) .withIdentity("currentTime-Job-1", "group1") .build(); //This trigger will run every minute in infinite loop Trigger trigger1 = TriggerBuilder.newTrigger() .withIdentity("everyMinuteTrigger", "group1") .startAt(new Date(System.currentTimeMillis())) .withSchedule( CronScheduleBuilder.cronSchedule( "0 0/1 * 1/1 * ? *")) .build(); Date ft = sched.scheduleJob(job1, trigger1); sched.start(); System.out.println(job1.getKey() + " has been scheduled to run at: " + ft); /** * Job 2 using SimpleTrigger */ JobDetail job2 = JobBuilder.newJob(DisplayCurrentTime.class) .withIdentity("currentTime-Job-2", "group1") .build(); // get a "nice round" time a few seconds in the future.... Date startTime = DateBuilder.nextGivenSecondDate(null, 10); //This trigger will run every 10 sec for 4 times SimpleTrigger trigger2 = TriggerBuilder.newTrigger() .withIdentity("fourTimesTrigger", "group1") .startAt(startTime) .withSchedule( SimpleScheduleBuilder.simpleSchedule() .withIntervalInSeconds(10) .withRepeatCount(4)) .build(); ft = sched.scheduleJob(job2, trigger2); sched.start(); System.out.println(job1.getKey() + " has been scheduled to run at: " + ft); /** * Job 3 Using CronTrigger */ JobDetail job3 = JobBuilder.newJob(DisplayCurrentTime.class) .withIdentity("currentTime-Job-3", "newGroup") .build(); //run every 20 seconds CronTrigger trigger3 = TriggerBuilder.newTrigger() .withIdentity("twentySec", "group2") .withSchedule( CronScheduleBuilder.cronSchedule( "0/20 * * * * ?")) .build(); ft = sched.scheduleJob(job3, trigger3); sched.start(); } catch (SchedulerException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } }
As you can see in above program, we have created the object of “StdSchedulerFactory“, which will schedule the job.
Then we have created the job and trigger to be executed by quartz framework.
In above example we have created three jobs and triggers.
While creating job, we specify that which class (implements interface Job) will be executed by framework. And the “JobName” and “Thread group” in which it will be executed.
We have used three types of trigger in above example:
- Trigger
- SimpleTrigger
- CronTrigger
- First trigger will execute every minute in infinite loop.
- Second trigger will execute in every 10 sec for 4 times.
- Third trigger will execute every 20 sec in infinite loop.
As you can observe, Trigger 1 and Trigger 3 are scheduled using “Cron Expressions“.
To create the Cron Expression easily or explain the cron expression, please refer this website.
Read more about Cron Expression at WIKI.
The output of the program will be like :
group1.currentTime-Job-1 has been scheduled to run at: Thu Sep 22 18:35:00 IST 2011
group1.currentTime-Job-1 has been scheduled to run at: Thu Sep 22 18:34:40 IST 2011
Job Name – group1.currentTime-Job-2, Current Time – 22 September 2011 – 18:34:40 PM
Job Name – newGroup.currentTime-Job-3, Current Time – 22 September 2011 – 18:34:40 PM
Job Name – group1.currentTime-Job-2, Current Time – 22 September 2011 – 18:34:50 PM
Job Name – group1.currentTime-Job-1, Current Time – 22 September 2011 – 18:35:00 PM
Job Name – group1.currentTime-Job-2, Current Time – 22 September 2011 – 18:35:00 PM
Job Name – newGroup.currentTime-Job-3, Current Time – 22 September 2011 – 18:35:00 PM
Job Name – group1.currentTime-Job-2, Current Time – 22 September 2011 – 18:35:10 PM
Job Name – group1.currentTime-Job-2, Current Time – 22 September 2011 – 18:35:20 PM
Job Name – newGroup.currentTime-Job-3, Current Time – 22 September 2011 – 18:35:20 PM
Download Quartz Source code and change extension from txt to rar
Leave a Reply to JitendraZaaCancel reply