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.
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.
The Unix cron expression is highly flexible and powerful, you can learn and see many cron expression examples in following websites.
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);
}
}
In your full example SimpleTrigger have no name it give the exception *Trigger’s name cannot be null*
You can add Trigger name as:
trigger.setName(“SampleTrigger”);
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.
Hi, as JobDetail is now an interface so can’t create object of this now.
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?
What are the advantages of using spring wrapper classes like JobDetailFactoryBean, CronTriggerFactoryBean over simple quartz JobDetail and Triggers etc.
In “5. Full Example”, “trigger.setName(“dummyTriggerName”);” is missing.
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.
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 * * * * ?”))
.build();
StdSchedulerFactory std = new StdSchedulerFactory();
Properties prop = new Properties();
prop.load(new FileInputStream(“./myquartz.properties”));
std.initialize(prop);
Scheduler scheduler = std.getScheduler();
scheduler.scheduleJob(job, trigger);
scheduler.start();
My quartz.properties file is as below even by default scheduler instance it works.
org.quartz.scheduler.instanceName: MyScheduler
org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount: 10
org.quartz.threadPool.threadPriority: 5
Any thoughts in this regard would be appreciable.
Thanks, Sri
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
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??
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
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.*;
iam new to the quartz scheduling ,how can we set quartz properties,should we create an XML file for that?
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 AM org.quartz.core.ErrorLogger schedulerError
SEVERE: An error occured instantiating job to be executed. job= ‘DEFAULT.dummyJobName’
org.quartz.SchedulerException: Problem instantiating class ‘com.java.scheduler.HelloJob1’ [See nested exception: java.lang.IllegalAccessException: Class org.quartz.simpl.SimpleJobFactory can not access a member of class com.java.scheduler.HelloJob1 with modifiers “”]
at org.quartz.simpl.SimpleJobFactory.newJob(SimpleJobFactory.java:57)
at org.quartz.core.JobRunShell.initialize(JobRunShell.java:132)
at org.quartz.core.QuartzSchedulerThread.run(QuartzSchedulerThread.java:387)
Caused by: java.lang.IllegalAccessException: Class org.quartz.simpl.SimpleJobFactory can not access a member of class com.java.scheduler.HelloJob1 with modifiers “”
at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
at java.lang.Class.newInstance0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at org.quartz.simpl.SimpleJobFactory.newJob(SimpleJobFactory.java:55)
… 2 more
Apr 03, 2013 12:23:00 AM org.quartz.simpl.RAMJobStore triggeredJobComplete
INFO: All triggers of Job DEFAULT.dummyJobName set to ERROR state.
I am getting this exception…please any body help to sort out this problem..
Thanks in advance.
Can you Please,
give me the Quartz misfire jobs Example.
how should i fix this error? “org.quartz.CronTrigger is abstract; cannot be instantiated”. Help!
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”
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
What’s the error? Btw, Quartz 2 APIs are big different with Quartz 1.5
“org.quartz.scheduler.instanceName = MyScheduler
org.quartz.threadPool.threadCount = 3
org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
org.quartz.plugin.jobInitializer.class =org.quartz.plugins.xml.XMLSchedulingDataProcessorPlugin
org.quartz.plugin.jobInitializer.fileNames = quartz-config.xml
org.quartz.plugin.jobInitializer.failOnFileNotFound = true”
how can we create a quartz.properties file using eclipse
wat is the mapping should be done in web.xml
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?
After Downloading the code – the main directory is Spring example. Do we need Springs framework to run this code?
My mistake, forgot to rename the folder, you DON’T need Spring to run Quartz.
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.
In Java scheduler, you don’t have much choices. Uses Quartz, enterprise job scheduler ~
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.”
q7NhOS+6lQLF6o8WVTn/Ke9GoduC4aSwfs5u0ZKsYBWIoaVhWRCzrWt89rYYrLrtpHMX2Be9jGuIhRydYjBnq6CFqC2/HadKsj47tVP4yuG+w32Sldu6YnuVhcZ6n02/FdGB1w==
sorry
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?
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
If thing need to be in schedule mode, that means it’s not a “request on demand” thing. My advice is create a standalone scheduler project which only focus on scheduling, and put it on a dedicated server.
Java –
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
You can reference it with the “Full Example” section, or download the project and compare with yours.
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
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.
ClassNotFoundException: org.apache.commons… you need common log jar.
Thanks.. this was very useful.
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.
For question not related to the article, try post here – Java Q&A forum
JobDetail is (now?) an interface.
now? What you means?
Probably when the article was written, JobDetail was a class. It is now an interface and cannot be used as described in step 3.
Exactly the problem being faced by me. I am just learning Quartz and it would be great if u could update this example using JobDetail as an Interface.