Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Scheduling Spring application using Quartz

In this article we will see the scheduling of Spring application using Quartz scheduler

At times, the applications need to be executed without any user intervention, like running a background process at specified intervals. Scheduling is needed if you want to automate the repetition of a task at specific intervals or particular date. You could of course manually watch the time and execute your task, albeit an inefficient task. Who wants to watch the computer every 3 seconds just to hit the Enter key? I guess no one.

Say for example, a Virus Scanner application will be running in the background once in 2 days. Another example could be where a software application could connect to its server repository once in a day for any updates.

In the previous article http://mrbool.com/job-scheduling-in-spring-application-using-jdk-timer/28796 we saw how to schedule tasks in Spring application using the JDK timer. Here I shall discuss about scheduling the tasks using Quartz Scheduler.

Quartz is extremely robust and powerful scheduling tool with advanced features such as distributed transactions and persistent jobs, the scope of which is completely outside of this article.

Quartz uses Triggers, Jobs and JobDetail ro realize scheduling of all kinds of jobs. For the basic concepts behind Quartz, have a look at http://www.opensymphony.com/quartz. For convenience purposes, Spring offers a couple of classes that simplify usage of Quartz within Spring-based applications.

Let's write an example which will trigger an application for receiving work status for all the employees on all the business days (i.e from Monday till Friday) at 11 AM and 6PM.

Writing the service Using JobDeatil bean

JobDetail objects contain all information needed to run a job. Spring provides a so-called JobDetailBean that makes the JobDetail more of an actual JavaBean with sensible defaults.

Since the focus is more on explaining the advanced scheduling support, this service will do nothing other than printing on the console that the service has been invoked at appropriate hours.

Lisiting 1: StatusUpdateService.java

package com.mrbool;

import java.util.Date;

public class StatusUpdateService {
	public void updateStatus(){
System.out.println(new Date() + " Update status Service invoked");
}
}

Wrapping the service in a job bean

Job Details can be defined via two ways in Spring. By using MethodInvokingJobDetailFactoryBean or by extending QuartzJobBean. In this example, QuartzJobBean method has been used.

A Job Bean in Quartz encapsulates the task for execution and in our case, the task is simple, that is, calling the status update service. The code for the same is as below:

Lisitng 2: StatusUpdateJobBean.java

package com.mrbool;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class StatusUpdateJobBean extends QuartzJobBean{
private StatusUpdateService service;
@Override
protected void executeInternal(JobExecutionContext context)
throws JobExecutionException {
service.updateStatus();
}
public StatusUpdateService getService() {
return service;
}
public void setService(StatusUpdateService service) {
this.service = service;
}
}
  • Here the job bean extends QuartzJobBean
  • The method executeInternal() is overridden for a job to execute.
  • Note that later on in the configuration file we will see how the dependency between status update service and status update job bean is resolved.

Configuration

The configuration file provides the declaration of beans, wiring the dependency between beans as well the scheduling support for job execution. The configuration file is as below:

Lisitng 3 : quartz.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
 <!-- The bean that does the actual work -->
<bean id="statusUpdateService" class="com.mrbool.StatusUpdateService">
</bean>
<bean id="statusUpdateJob" class="com.mrbool.StatusUpdateJobBean">
</bean>
 <!--  A simple trigger:  statusUpdateTriggerBean
   See: 25.6.3 Wiring up jobs using triggers and the SchedulerFactoryBean
   @<http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html-->>
 <!-- For every second in every minute, but during 11 AM and 6 PM hours, for all the months ranging from Monday till Friday in every Year-->

<bean id="statusUpdateTriggerBean" 	class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="statusUpdateJob"/>
<property name="cronExpression" value="0 0 11,18 ? * MON-FRI *" />
</bean>
<!-- Schedules the jobs :
   Triggers need to be scheduled. Spring offers a SchedulerFactoryBean that exposes triggers to be set as properties. 
   SchedulerFactoryBean schedules the actual jobs with those triggers
   See: 25.6.3 Wiring up jobs using triggers and the SchedulerFactoryBean
   @<http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html> -->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers" >
<list>
<ref bean="statusUpdateTriggerBean"/>
</list>
</property>
</bean>
</beans>
  • The first bean declaration with the id statusUpdateService declares an instance of StatusUpdateService service which has the core logic for the execution of a job.
  • The declaration of JobDetailBean which is declared as follows:
  • 	<bean id="statusUpdateJob" class="com.mrbool.StatusUpdateJobBean">
    </bean>
    	
  • Triggers can also be defined via two ways in Spring. By defining SimpleTriggerBean or CronTriggerBean . When SimpleTriggerBean is used, jobDetail, repeatInterval and startDelay properties are defined. When CronTriggerBean is used, jobDetail and cronExpression properties are defined.
  • Here we have used the CronTriggerBean which will be acting as a scheduler providing the time period and interval on which the job has to be executed.
    <bean id="statusUpdateTriggerBean" 	class="org.springframework.scheduling.quartz.CronTriggerBean">
    <property name="jobDetail" ref="statusUpdateJob"/>
    <property name="cronExpression" value="0 0 11,18 ? * MON-FRI *" />
    	</bean>	
    
  • This bean takes the mandatory properties jobDetail and cronExpression. The property jobDetail takes a reference to the job detail object that was just declared. The cronExpression property specifies the interval at which the job has to be executed. Here the value given is “0 0 11,18 ? * MON-FRI *”. This value has 7 parts with space as a delimiter the meaning of which is given as follows:
    • First Field - Seconds
    • Second Field - Minutes
    • Third Field - Hours
    • Fourth Field - Day of the Month
    • Fifth Field - Month
    • Sixth Field - Day of week
    • Seventh Field - Year

Every value in the above field can either take a single value (Eg: 1), comma-separated (Eg: 1,3,5) or range-based (Eg: 1-10). There are wild-card charactes ‘*’ and ‘?’ carrying special meaning. When ‘*’ is used against a field, it indicates all the values.

For example, is ‘*’ is used for the third field, then it means for each hour. When ‘?’ is used it indicates that the field doesn’t carry any value.

Now coming back to our example, the value specified is “0 0 11,18 ? * MON-FRI *” which means “For every second in every minute, but during 11 AM and 6 PM hours, for all the months ranging from Monday till Friday in every Year” execute the given task.

Finally, Job Details and Triggers are configured by creating SchedulerFactoryBean. The SchedulerFactoryBean purpose is to schedule the actual jobs assigned in the triggers. Why do we need to have a scheduler, a trigger, and a job just to schedule a single task in Quartz?

Quartz uses Trigger, Job and JobDetail objects to realize scheduling of all kinds of jobs. For the basic concepts behind Quartz, have a look at http://www.opensymphony.com/quartz. For convenience purposes, Spring offers a couple of classes that simplify the usage of Quartz within Spring-based applications.

Conclusion:

In this article we saw the scheduling of Spring application using Quartz scheduler. We have seen how to write Job Scheduling applications with JDK Timer and Quartz scheduler in this article. It can be seen that for an application requiring basic scheduling support, it is wise to choose JDK Timer, however for applications that requires more sophisticated scheduling support; it is preferable to choose Quartz.



I''m a full stack developer with around 10+ yrs of experience. I enjoy writing technical articles on upcoming technical trends.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login