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

Job Scheduling in Spring Application using JDK Timer

In this article I shall discuss about how Spring provides integration support for JDK Timer that facilitates in writing job scheduling applications.

At times the applications need to be executed without any user intervention, like running a background process at specified intervals. 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 this article I shall discuss about how Spring provides integration support for JDK Timer that facilitates in writing job scheduling applications.

Integrating JDK Timer with Spring Framework

JDK Timer task objects provide support for execution of any tasks driven by a timer. Let us check an example for this as below:

Suppose we want to write a service that will periodically check for internet connection and log the connection status. Let's assume that this service has to run periodically all through the day with an interval of 30 minutes.

Following Jars are required to execute the example below:

  • log4j-1.2.13.jar
  • commons-logging-1.1.1.jar
  • spring-beans-3.2.4.RELEASE.jar
  • spring-context-3.2.4.RELEASE.jar
  • spring-context-support-3.2.4.RELEASE.jar
  • spring-core-3.2.4.RELEASE.jar
  • spring-expression-3.2.4.RELEASE.jar

Writing the service

Following class provides the listing representing the internet connection service.

Listing 1: CheckInternetConnectionService.java

package com.mrbool;

import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
public class CheckInternetConnectionService {
public void checkConnection(){
if (doCheck()){
System.out.println(new Date() + " Internet connection available");
}else{
System.out.println(new Date() + " Internet connection not 	available");
}
}
private boolean doCheck(){
URL urlObject = null;
URLConnection urlConnection = null;
try{
urlObject = new URL("http://www.google.com");
urlConnection = urlObject.openConnection();
urlConnection.getContent();
return true;
}catch (Exception exception){
return false;
}
}
}

The above code is fairly simple. In the method doCheck() we check whether internet connection is available and hence open up a connection to a well-known domain for getting the content. When the connection is not available, exception will be thrown.

Wrapping service as a timer task

Now that we have written a service, we will see how to time it. The code is as follows:

Listing 2: CheckInternetConnectionWithTimerTask

package com.mrbool;

import java.util.TimerTask;

public class CheckInternetConnectionWithTimerTask extends TimerTask {

	private CheckInternetConnectionService service;

	public CheckInternetConnectionService getService() {
		return service;
	}

	public void setService(CheckInternetConnectionService service) {
		this.service = service;
	}

	@Override
	public void run() {
		service.checkConnection();
	}

}
  • Here we see that the class extends java.util.TimerTask class.
  • The run() method is overridden for performing any operation. In this case, the run() method will be calling the internet
  • connection service to check for the connection status.
  • Note that timer task is dependant on internet connection service object. Later on, we will see how to wire both objects.

Configuration

So far we haven’t specified the repeating interval (of 30 minutes). Spring provides this support through configuration. Have a look at the following configuration file representing the application’s context.

Listing 3: timer.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">

<bean id="connectionCheckService" class="com.mrbool.CheckInternetConnectionService">
</bean>
<bean id="connectionCheckTimerTask" class="com.mrbool.CheckInternetConnectionWithTimerTask">
<property name="service" ref="connectionCheckService" />
</bean>
<bean id="scheduledConnectionCheckTimerTask" 	class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="delay" value="2000" />
<property name="period" value="30000" />
<property name="timerTask" ref="connectionCheckTimerTask" />
</bean>
<bean class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<ref bean="scheduledConnectionCheckTimerTask"/>
</list>
</property>
</bean>
</beans>

Details of the above configuration file is as below:

  • Here we see that the bean connectionCheckService is declared which represents the internet connection service.
  • The second bean declaration defines the timer task with the bean id connectionCheckTimerTask. Because timer task is dependent on internet connection service, the dependency is injected through configuration.

Take a look at the following code snippet which declares the scheduled timer task object from Spring.

<bean id="scheduledConnectionCheckTimerTask" 	class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="delay" value="2000" />
<property name="period" value="30000" />
<property name="timerTask" ref="connectionCheckTimerTask" />
</bean>
  • The class org.springframework.scheduling.timer.ScheduledTimerTask provides scheduling support for the execution of timer tasks.
  • The property delay is specified in milliseconds. It specifies the initial delay after which the task has to be executed. The value is mentioned as 2000 which means the initial delay for the execution of the task will be 2 seconds.
  • Next comes the property period which is also specified in milliseconds and that represents the interval after which the task will be repeatedly executed. In our case, the value given is 3000, so after every 30 minutes the task for execution will be fired.
  • The final property is the timerTask which should point to the actual timer task object, in this case it is going to be the connectionCheckTimerTask.

Triggering the scheduled tasks is done by TimerFactoryBean. This takes a list of scheduled timer task objects, in our case there is only one scheduled timer task object which is scheduledConnectionCheckTimerTask.

<bean class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<ref bean="scheduledConnectionCheckTimerTask"/>
</list>
</property>
</bean>

Client

The client application in this example will load the application’s context. As soon as the context is loaded the service object, timer task object, scheduled timer task objects will be loaded and wired. Because we have also introduced the trigger bean which will trigger the scheduled timer task for execution, the internet connection will be running indefinitely with an interval of 30 minutes.

Listing 4: Client.java

package com.mrbool;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Client {
	public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("timer.xml");
}
}

Now execute the Client.java either from your command prompt or in any of your IDEs, the trigger bean triggers the scheduled timer task for execution, and executes indefinitely with an interval period of 30 minutes.

Conclusion

Here we saw how to schedule your task in Spring applications using the JDK timer. In the next article I shall discuss about the scheduling the tasks using 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