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
44 Comment threads
23 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
43 Comment authors
Akshit AgarwalAnand JOisMohd WaseemRaghav SharmaSrini Recent comment authors
newest oldest most voted
Raghav Sharma
Guest
Raghav Sharma

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

Akshit Agarwal
Guest
Akshit Agarwal

You can add Trigger name as:

trigger.setName(“SampleTrigger”);

Anand JOis
Guest
Anand JOis

Hi,
I want to schedule my java main program. i did all the steps and it works fine but my test environment does not have eclipse and I can only deploy my code and make it run either windows scheduler or through a jar file. How should I schedule it Could you please guide me on this?

Mohd Waseem
Guest
Mohd Waseem

What are the advantages of using spring wrapper classes like JobDetailFactoryBean, CronTriggerFactoryBean over simple quartz JobDetail and Triggers etc.

Srini
Guest
Srini

In “5. Full Example”, “trigger.setName(“dummyTriggerName”);” is missing.

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.

revathi
Guest
revathi

I am getting an error like org.quartz is not resolved.I imported quartz jar 1.8.5.How to solve my issue ,Can you please resolve it.

srinivas
Guest
srinivas

Hi, I am able to schedule the job as given above in a standalone program, I am trying to shut down the job when ever I required so written another java program but the scheduler unable to get the handle to delete the job or interrupt the job or unschedule. Implemented InterruptableJob for the job. Tried through initializing the Properties file. The Below code works as expected, but unable to stop the job through standalone. JobDetail job = JobBuilder.newJob(BatchSchedulerJOB.class) .withIdentity(“MJob”, “MGroup”).build(); TriggerKey key = new TriggerKey(“MGroup.MTrigger”); Trigger trigger = TriggerBuilder .newTrigger().withIdentity(key) //.withIdentity(“MTrigger”, “MGroup”) .forJob(job) .withSchedule( CronScheduleBuilder.cronSchedule(“59 * * * *… Read more »

HuongDT
Guest
HuongDT

I use quartz(ver 2.1.0) for my bundle in OSGIFW, but when use
SchedulerFactory sf = new StdSchedulerFactory()
sched = sf.getScheduler()
i got an error:
-> org.quartz.SchedulerConfigException: Unable to instantiate class load helper class: org.quartz.simpl.CascadingClassLoadHelper cannot be cast to org.quartz.spi.ClassLoadHelper [See nested exception: java.lang.ClassCastException: org.quartz.simpl.CascadingClassLoadHelper cannot be cast to org.quartz.spi.ClassLoadHelper]

i try to find another quartz library in my location, but has only one (that jar file)

Any idea how correct this ?

Thanks

thanooj
Guest
thanooj

How to handle a job when we do
sched.interrupt(jobName , jobGroup);

I need to get the status of a job when it got interrupted. is there any Job Handlers are available??

Sushant
Guest
Sushant

Hi,
I am getting error in almost every line
method setname(String) is undefined for type JobDetail
method setJobClass(Class) is undefined for type JobDetail

and same with the methods of SimpleTrigger.

please help.
i m using Quarts 2.1.7

Siva Pathiwada
Guest
Siva Pathiwada

Quartz 2 APIs are big different with Quartz 1(1.5,1.6 and 1.7) Class JobDetail{
}

quartz-1.6.6:
http://javasourcecode.org/html/open-source/quartz/quartz-1.6.6/org/quartz/JobDetail.html

Quartz 2:
public interface JobDetail extends Serializable, Cloneable {
}

// we have to create JobDetail in the below way.
JobDetail job = newJob(HelloJob.class)

// we have to create Trigger in the below way.
Trigger trigger = newTrigger()

Don’t foget to improt the below one
import static org.quartz.JobBuilder.*;
import static org.quartz.TriggerBuilder.*;

trackback
is possible work with 2 schedule with the same Timer : Android Community - For Application Development
Midhun jose
Guest
Midhun jose

iam new to the quartz scheduling ,how can we set quartz properties,should we create an XML file for that?

vijay
Guest
vijay

Apr 03, 2013 12:22:48 AM org.quartz.simpl.SimpleThreadPool initialize INFO: Job execution threads will use class loader of thread: main Apr 03, 2013 12:22:48 AM org.quartz.core.SchedulerSignalerImpl INFO: Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl Apr 03, 2013 12:22:48 AM org.quartz.core.QuartzScheduler INFO: Quartz Scheduler v.1.6.3 created. Apr 03, 2013 12:22:48 AM org.quartz.simpl.RAMJobStore initialize INFO: RAMJobStore initialized. Apr 03, 2013 12:22:48 AM org.quartz.impl.StdSchedulerFactory instantiate INFO: Quartz scheduler ‘DefaultQuartzScheduler’ initialized from default resource file in Quartz package: ‘quartz.properties’ Apr 03, 2013 12:22:48 AM org.quartz.impl.StdSchedulerFactory instantiate INFO: Quartz scheduler version: 1.6.3 Apr 03, 2013 12:22:48 AM org.quartz.core.QuartzScheduler start INFO: Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started. Apr 03, 2013 12:23:00… Read more »

Mitul
Guest
Mitul

Can you Please,
give me the Quartz misfire jobs Example.

Poonam
Guest
Poonam

how should i fix this error? “org.quartz.CronTrigger is abstract; cannot be instantiated”. Help!

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”

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

trackback
Quartz Scheduler Tutorial ‹ ???

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

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. […]

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?

sangram
Guest
sangram

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

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.

trackback
??? » 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.”

sir
Guest
sir

q7NhOS+6lQLF6o8WVTn/Ke9GoduC4aSwfs5u0ZKsYBWIoaVhWRCzrWt89rYYrLrtpHMX2Be9jGuIhRydYjBnq6CFqC2/HadKsj47tVP4yuG+w32Sldu6YnuVhcZ6n02/FdGB1w==

xxx
Guest
xxx

sorry

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?

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

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

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

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!). […]