Quartz 1.6 scheduler tutorial

Quartz is a powerful and advance scheduler framework, to help Java developer to scheduler a job to run at a specified date and time.

This tutorial show you how to develop a scheduler job using Quartz 1.6.3.

Note
This example is a bit outdate, unless you are still using the old Quartz 1.6.3 library, otherwise, you may interest of this latest Quartz 2.1.5 example.

1. Download Quartz

You can get the Quartz library from official website or Maven central repository

File : pom.xml


	<dependencies>

		<!-- Quartz API -->
		<dependency>
			<groupId>opensymphony</groupId>
			<artifactId>quartz</artifactId>
			<version>1.6.3</version>
		</dependency>

		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>

		<dependency>
			<groupId>org.apache.directory.studio</groupId>
			<artifactId>org.apache.commons.logging</artifactId>
			<version>1.1.1</version>
		</dependency>

	</dependencies>

2. Quartz Job

Quartz job is defined what you want to run?

File : HelloJob


package com.mkyong.common;

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!");	
		
	}
	
}

3. Quartz Trigger

Quartz trigger is defined when the Quartz will run your above Quartz’s job?

There are two types of Quartz triggers :

  • SimpleTrigger – Allows to set start time, end time, repeat interval.
  • CronTrigger – Allows Unix cron expression to specify the dates and times to run your job.
Unix cron expression
The Unix cron expression is highly flexible and powerful, you can learn and see many cron expression examples in following websites.

  1. http://en.wikipedia.org/wiki/CRON_expression
  2. http://www.quartz-scheduler.org/docs/examples/Example3.html

SimpleTrigger – Run every 30 seconds.


        SimpleTrigger trigger = new SimpleTrigger();
    	trigger.setName("dummyTriggerName");
    	trigger.setStartTime(new Date(System.currentTimeMillis() + 1000));
    	trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
    	trigger.setRepeatInterval(30000);

CronTrigger – Run every 30 seconds.


    	CronTrigger trigger = new CronTrigger();
    	trigger.setName("dummyTriggerName");
    	trigger.setCronExpression("0/30 * * * * ?");

4. Scheduler

Scheduler class links both “Job” and “Trigger” together and execute it.


    	Scheduler scheduler = new StdSchedulerFactory().getScheduler();
    	scheduler.start();
    	scheduler.scheduleJob(job, trigger);

5. Full Example

Here are two full examples to use Quartz, via SimpleTrigger and CronTrigger.

SimpleTrigger example
Run very 30 seconds with a 1 second delay for the first time of execution.


package com.mkyong.common;

import java.util.Date;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;

public class SimpleTriggerExample 
{
    public static void main( String[] args ) throws Exception
    {
       	JobDetail job = new JobDetail();
    	job.setName("dummyJobName");
    	job.setJobClass(HelloJob.class);
    	
    	//configure the scheduler time
    	SimpleTrigger trigger = new SimpleTrigger();
    	trigger.setStartTime(new Date(System.currentTimeMillis() + 1000));
    	trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
    	trigger.setRepeatInterval(30000);
    	
    	//schedule it
    	Scheduler scheduler = new StdSchedulerFactory().getScheduler();
    	scheduler.start();
    	scheduler.scheduleJob(job, trigger);

    }
}

CronTrigger example
Same, run the job at every 30 seconds.


package com.mkyong.common;

import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.impl.StdSchedulerFactory;

public class CronTriggerExample 
{
    public static void main( String[] args ) throws Exception
    {
    	
    	JobDetail job = new JobDetail();
    	job.setName("dummyJobName");
    	job.setJobClass(HelloJob.class);
    	    	
    	CronTrigger trigger = new CronTrigger();
    	trigger.setName("dummyTriggerName");
    	trigger.setCronExpression("0/30 * * * * ?");
    	
    	//schedule it
    	Scheduler scheduler = new StdSchedulerFactory().getScheduler();
    	scheduler.start();
    	scheduler.scheduleJob(job, trigger);
    
    }
}

Download Source Code

Download it – QuartzExample.zip (14kb)

References

  1. Quartz Official Website

About the Author

author image
mkyong
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

avatar
45 Comment threads
23 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
44 Comment authors
akshayAkshit AgarwalAnand JOisMohd WaseemRaghav Sharma Recent comment authors
newest oldest most voted
PA
Guest
PA

Hi Mkyong,
It seems that for latest Quartz version (2.2.1), you can not instantiate “JobDetail”. I think need to update all these tutorials. I’d like to help you on this.

Raghav Sharma
Guest
Raghav Sharma

In your full example SimpleTrigger have no name it give the exception *Trigger’s name cannot be null*

trackback
Spring + Quartz scheduler example | Spring

[…] handy classes to support the Quartz, and decouple your class to Quartz API. P.S You can check the Quartz without Spring support example here. Download this Spring’s Quartz example here – […]

Seamus
Guest
Seamus

Use the new dependency information…

groupId – org.quartz-scheduler
artifactId – quartz
version – 1.7.3

trackback
Quartz scheduler example | Java « Lubos Blogs

[…] Posted on April 6, 2010. Filed under: Uncategorized | Excellent short tutorial of Quartz scheduler Quartz scheduler example | Java. […]

trackback
Blog bookmarks 04/07/2010 « My Diigo bookmarks

[…] Quartz scheduler example | Java […]

trackback
Struts + Quartz scheduler integration example | Struts

[…] Please visit this Quartz scheduler example to learn the basic usage of the Quartz […]

Mr. Mendoza
Guest
Mr. Mendoza

Hi, how I can recover the CronExpressions assigned? regards.

trackback
Struts 2 + Quartz scheduler integration example

[…] Quartz scheduler example […]

milos
Guest
milos

Can you do DB queries with Quartz without using Spring? I get WARNING:

“Using job-store ‘org.quartz.simpl.RAMJobStore’ – which does not support persistence. and is not clustered.”

_neo_
Guest
_neo_

Is there any way to determine next run time of job?

Galih
Guest
Galih

how to execute or fire directly the job Class without trigger the scheduler quartz?
what if i just call the job class in other class?
Thanks..

Otto
Guest
Otto

JobDetail is (now?) an interface.

latha
Guest
latha

Can you please help me out? Can I able to schedule a Job which calls servlet and get data for me? (Actually this is my situation)
Job—> calls—> servlet
from there getting data back.
Please please help me.I am struck here.

Sylar
Guest
Sylar

Thanks.. this was very useful.

Amar
Guest
Amar

I get this error, when I try to execute Quartz-Scheduler-Example\QuartzAppCronTrigger class file.

Exception in thread “main” java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
at org.quartz.impl.StdSchedulerFactory.(StdSchedulerFactory.java:249)
at com.mkyong.common.QuartzAppCronTrigger.main(QuartzAppCronTrigger.java:30)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
… 2 more

I get following error when I am trying to update maven dependencies –
9/19/11 11:35:43 AM IST: [WARN] The POM for opensymphony:quartz:jar:1.6.3 is missing, no dependency information available

Thanks for your help in advance.

trackback
Quartz.net Simple Example | trouble86.com

[…] http://www.mkyong.com/java/quartz-scheduler-example/ – Java, so hard for me to understand the difference (Im new to all this!). […]

ican
Guest
ican

Hi,

can this code use for current time?
i want to make my code run at 02:00 AM for example, can this code do this?

Fast replay will be great, Thanks

Rahul Awasthi
Guest
Rahul Awasthi

Java –

3. Scheduler JobDetail

 RunMeTask task = new RunMeTask();
 
    	//specify your sceduler task details
    	JobDetail job = new JobDetail();
    	job.setName("runMeJob");
    	job.setJobClass(RunMeJob.class);
 
    	Map dataMap = job.getJobDataMap();
    	dataMap.put("runMeTask", task);

i have done upto first 2 steps,,but in 3rd step,,where i have to put ur code of step 3 is it in step 2 class or i have to make a new class for step 3 code..,,,i m very new in java,,,so plz help me…

thanks in advance

sd
Guest
sd

This is regarding spring Quartz scheduled job in high availability configuration.

If I were to deploy the spring application on 2 nodes and need the quartz scheduled job to run on only one node at any given time, then how can this be achieved.

Thanks

BIP
Guest
BIP

I need to kick of job using Quartz when ever there is an update in our source DB tables. How can we implement using Controm M scheduler with Quartz?

zgdk
Guest
zgdk

From Best Practices on Quartz-Scheduler.org: “Only store primitive data types (including Strings) in JobDataMap to avoid data serialization issues short and long-term.”

trackback
??? » Quartz
rajneekanth
Guest
rajneekanth

hi Mkyong,

I am doing a study for selecting a suitable scheduler for my project. as part of this I got your page. can you help me to get the below information.

1) What is the Request and Response Interface? Corba/RMI/java API ?
2) any Scalability Issues ? like we may need to schedule 30K, 40K and 50K jobs now. tomorrow it may increase to more.
3) any Performance Issues ?
4) what is the DataBase it uses internally?
5) any Pros/cons
6) Remarks

Thanks for your time.

sangram
Guest
sangram

After Downloading the code – the main directory is Spring example. Do we need Springs framework to run this code?

Migdalia Ahonen
Guest
Migdalia Ahonen

Great amazing issues here. I am very satisfied to see your article. Thanks so much and i’m looking forward to touch you. Will you please drop me a e-mail?

trackback
Quartz 2 scheduler tutorial

[…] This tutorial show you how to develop a scheduler job using latest Quartz library 2.1.5. Note Quartz 2 involves significant API changes since 1.x, read this for older Quartz 1.6.3 example. […]

trackback
Quartz Scheduler Tutorial ‹ ???

[…] Quartz 1.6 hello world example The old and popular Quartz 1.6.3, legacy system may still using this. […]

naxelou
Guest
naxelou

to schedule with a specific dans of the month , I try to use the quartz 2.1 instead of quartz 1.5 but it cause an error in scheduler.getJobDtail , how can I resolve the problem

danny
Guest
danny

java.lang.UnsupportedClassVersionError: Bad version number in .class file
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
Exception in thread “main”