Spring + Quartz scheduler example
In this tutorial, we show you how to integrate Spring with popular scheduler framework – Quartz. Spring comes with many handy classes to support the Quartz, and decouple your class to Quartz API.
1. Scheduler Task
Create a normal Java class, this is the class you want to schedule.
package com.mkyong.common; public class RunMeTask { public void printMe() { System.out.println("Run Me ~"); } }
Bean configuration file.
<bean id="runMeTask" class="com.mkyong.common.RunMeTask" />2. Scheduler Job + JobDetail
With Spring support, you can declare the Quartz job in two ways :
2.1 MethodInvokingJobDetailFactoryBean
This is the simplest and straightforward method, suitable for simple scheduler. You can specify a ‘MethodInvokingJobDetailFactoryBean‘ class to configure the class and method you want to schedule.
<bean id="runMeJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="runMeTask" /> <property name="targetMethod" value="printMe" /> </bean>
2.2 JobDetailBean
The QuartzJobBean is more flexible and suitable for complex scheduler. You need to create a class extends the Spring’s QuartzJobBean, and define the method you want to schedule in executeInternal() method, and pass the scheduler task (RunMeTask) via setter method.
package com.mkyong.common; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.scheduling.quartz.QuartzJobBean; public class RunMeJob extends QuartzJobBean { private RunMeTask runMeTask; public void setRunMeTask(RunMeTask runMeTask) { this.runMeTask = runMeTask; } protected void executeInternal(JobExecutionContext context) throws JobExecutionException { runMeTask.printMe(); } }
Configure the target class (jobClass) and method (jobDataAsMap).
<bean name="runMeJob" class="org.springframework.scheduling.quartz.JobDetailBean"> <property name="jobClass" value="com.mkyong.common.RunMeJob" /> <property name="jobDataAsMap"> <map> <entry key="runMeTask" value-ref="runMeTask" /> </map> </property> </bean>
3. Trigger
Configure the Quartz trigger to define when will run your scheduler job. Two type of triggers are supported :
3.1 SimpleTrigger
It allows to set the start time, end time, repeat interval to run your job. In this simpleTrigger example, it will run the printMe() method in every 5 seconds with a 1 second delay for the first time of execution.
<!-- Simple Trigger --> <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"> <property name="jobDetail" ref="runMeJob" /> <property name="repeatInterval" value="5000" /> <property name="startDelay" value="1000" /> </bean>
3.2 CronTrigger
It allows Unix cron expression to specify the dates and times to run your job. In this cronTrigger example, it will run the printMe() method in every 5 seconds.
<!-- Cron Trigger --> <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="runMeJob" /> <property name="cronExpression" value="0/5 * * * * ?" /> </bean>
The Unix cron expression is highly flexible and powerful, you can learn and see many advance cron expression examples in following website.
- http://en.wikipedia.org/wiki/CRON_expression
- http://www.quartz-scheduler.org/docs/examples/Example3.html
4 Scheduler
Create a Scheduler factory bean to integrate your job detail and trigger together.
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="jobDetails"> <list> <ref bean="runMeJob" /> </list> </property> <property name="triggers"> <list> <ref bean="simpleTrigger" /> </list> </property> </bean>
Full Spring’s bean configuration file
Spring-Quartz.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="runMeTask" class="com.mkyong.common.RunMeTask" /> <bean name="runMeJob" class="org.springframework.scheduling.quartz.JobDetailBean"> <property name="jobClass" value="com.mkyong.common.RunMeJob" /> <property name="jobDataAsMap"> <map> <entry key="runMeTask" value-ref="runMeTask" /> </map> </property> </bean> <!-- <bean id="runMeJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="runMeTask" /> <property name="targetMethod" value="printMe" /> </bean> --> <!-- Simple Trigger --> <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"> <property name="jobDetail" ref="runMeJob" /> <property name="repeatInterval" value="5000" /> <property name="startDelay" value="1000" /> </bean> <!-- Cron Trigger --> <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="runMeJob" /> <property name="cronExpression" value="0/5 * * * * ?" /> </bean> <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="jobDetails"> <list> <ref bean="runMeJob" /> </list> </property> <property name="triggers"> <list> <ref bean="simpleTrigger" /> </list> </property> </bean> </beans>
Run it
package com.mkyong.common; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main( String[] args ) throws Exception { new ClassPathXmlApplicationContext("Spring-Quartz.xml"); } }
Done.





Nice work, I have been using annotation and trying to update some old apps which still in 2.5. Anyway, if just need to trigger a method in a particular object, it will be cleaner to use the MethodInvokingJobDetailFactoryBean. Then there is no need to extends the quartz detail.
http://static.springsource.org/spring/docs/2.5.x/reference/scheduling.html
love you site, alot of useful information. thanks
Hi,
This method works fine but I want servletContext object in the quartz job. I can I do that ?
How can I retrieve servletContext reference in executeInternal() method ??
Thanx,
Gunjan.
Great tutorial! I’ve been swimming around in manuals for the last few hrs, but this one example not only worked but it clarified all of the past day’s reading! thx!
And… i’ve one question, after i run it with:
how do i stop it?
Anyway, thanks. Very Good Post.
I wonder if it’s possible somehow to use the JobDetailFactoryBean (because is exposes the JobExecutionContext) and do everything with less XML than today…
Passing in services via jobDataAsMap is not really pretty compared to using the MethodInvokingJobDetailFactoryBean that allows for normal @Autowired annotations.
If seen that one could pass arguments along with the targetMethod, but these appear fixed upon preparation time of the method invoker… There’s no way (except rewriting the whole MethodInvokingJobDetailFactoryBean as I’ve not seen a good way to inject just some behaviour…) to pass the JobExecutionContext into a scheduled bean used with MethodInvokingJobDetailFactoryBean yet…
Maybe there’s a solution, but I’ve not seen it yet.
while i am running quartz timer service i got this error.If any knows could u help to solve this problem
Exception in thread “main” org.springframework.beans.factory.BeanCreationExcepti
on: Error creating bean with name ‘jdb’ defined in class path resource [spconfig
.xml]: Instantiation of bean failed; nested exception is org.springframework.bea
ns.BeanInstantiationException: Could not instantiate bean class [org.springframe
work.scheduling.quartz.JobDetailBean]: Constructor threw exception; nested excep
tion is java.lang.NoClassDefFoundError: org/apache/commons/collections/SetUtils
Can I ask which versions of quartz and spring you used for this tutorial? I have been trying with Spring 3.1 and Quartz 2.1 but I get errors and when looking in the 3.1 release notes it mentions that it should work with Quartz 2.1.
The error I get is as follows:
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.CannotLoadBeanClassException: Error loading class [org.springframework.scheduling.quartz.JobDetailBean] for bean with name ‘runMeJob’ defined in ServletContext resource [/WEB-INF/quartz-servlet.xml]: problem with class file or dependent class; nested exception is java.lang.IncompatibleClassChangeError: class org.springframework.scheduling.quartz.JobDetailBean has interface org.quartz.JobDetail as super class
Use JobDetail”Factory”Bean. Some of the old “…Bean” won’t work with Quartz 2.x, the “…FactoryBean” will work with all versions according to the Spring Javadoc.
HI,
I manage to run your code on JBOSS but when change the name of runJob and runTask to something else its giving me null value exception in executeInternal method.
I replace the above two values in applicationcontext.xml and in respective java classes as well.
am I missing some place more where i need to change them?
Hi Mkyong,
I am able to set the scheduler by using cronjobtriggerbean but not able to schedule multiple jobs using cronjobtriggerbean. Seems to be possible of triggering one job ony. Is my understanding correct?
Hi,
Thanks for this consolidated tutorial. But my quartz xml file shows an error saying that no setter found for property repeatInterval in org.springframework.scheduling.quartz.SimpleTriggerBean ,I am using spring 3.1 jar , and when i decompiled simpletriggerbean, i saw that there was no property called repeatInterval, Is this error of spring version? or something else?
I have the same problem. If you find a solution, e-mail me…
Did you find solution. There is no repeatInterval property.
Thanks.
hi,
i try in my eclipse buy its thrown a error,
Please help….
add slf4j to your classpath
[...] Using Java Service Wrapper, the compleceted steps above can be simplified. The case study is scehduler will print log every one second. To know about quartz using spring support please check this article [...]
[...] Using Java Service Wrapper, the complecated steps above can be simplified. The case study is scehduller will print log every one second. To know about quartz using spring support please check this article [...]
Hi. I understand completely your tutorial. It is very well explained.
However, I have some questions regarding this approach.
For example, I created a job and scheduled it to run every after 15 mins.
I have done it since your tutorial did an excellent job in explaining.
How would I do it if I want an external factor to trigger the start of that job?
In a casual way it goes like this:
I have a function:
void checkEvery15Minutes();
Let’s say that all the configurations of this function is set using beans and all.
It will execute with an interval of 15 mins.
And I have another function:
boolean isInboxEmpty();
I want to do this:
if(isInboxEmpty()==false) {
checkEvery15Mins();
}
I want only the checkEvery15Mins function to start only if my inbox is empty.
is this possible?
THANKS! :)
Don’t think it is possible in Quartz, alternatively, you can create 2 schedulers :
1. isInboxEmptyScheduler() run every seconds (not recommend), and insert a flag into db if inbox is empty, otherwise delete the flag;
2. checkEvery15MinsScheduler() run every 15min, take the flag from db to indicate whether continue the function.
Hi mkyong,
I’m newbie to Spring tech. The Spring scheduler example worked for me.
It’d be great if you provided the Spring3.0 ‘annotation’ based example.
Once again applause for your blog/work.
Regards,
Sripad.
Spring 2.5.x n 3 annotation is not much big different, you can view some of the examples in http://www.mkyong.com/tutorials/spring-tutorials/ . Still preparing the Spring 3 examples.
I want the scheduler to run automatically with out starting from main method. How could I do that? Please explain
Integrate quartz with Spring, put spring loader in your web.xml, and it will start automatically when your web application is started.
Hi mykyong,
I too have the same query. If i need to call the scheduler without calling main, in my already implemented spring code. How do i go about it?
by integrate quartz with Spring, put loader in web.xml do you mean this?
contextConfigLocation
/WEB-INF/applicationContext.xml
/WEB-INF/applicationContext-security.xml
/WEB-INF/Spring-Quartz.xml
I have done this, but I dont see the scheduler working.
Please help.
Replied you via email. Just copied the answer here :)
By default, Spring will look for “applicationContext.xml” in your classpth, so include it into the ” contextConfigLocation” is optional, unless you have a different file name , like “ABCDEFGapplicationContext.xml”.
In this case, you should link “Spring-Quartz.xml” into your “applicationContext.xml” , see this article – http://www.mkyong.com/spring/load-multiple-spring-bean-configuration-file/ , via “import resource” tag. And put “applicationContext.xml” in your class path, Spring will find it automatically. And of course, delete the settings in web.xml.
Great blog and thanks for the ideas. You gave me ambitionto write another blog post later on. I like your style.
+1, works out of the box in my webapp, thanks for the easy to follow tutorial!
Thanks…this was very useful!
Very good example. It worked well. Thanks so much.
Hi Mkyong, It is really good article, keep it up!!!.
I follow your article for my project. It works like a charm.
[...] Spring + Quartz scheduler example Article about how Spring schedule a job with Quartz framework. [...]
Thanks a lot for posting this. This is a great tutorial and I have been pulling my hair out trying to learn Spring and Quartz!
Nice material regarding spring and quartz, thank you for the posting.
I had gone through your example and found that it is working fine as a stand-alone application!
But without the web archive help this can not be deployed on container.
Or if I am wrong what is the way to deploy this on container so that the job will run as per scheduled?
Do you means web container? You can integrate Spring with normal servlet web application or other frameworks via this generic method
http://www.mkyong.com/spring/spring-how-to-do-dependency-injection-in-your-session-listener/
or Struts framework
http://www.mkyong.com/struts/struts-spring-integration-example/