HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Spring Core / Spring Timer Tasks

Spring Timer Tasks

Timer is a utility class which is used to schedule tasks for both one time and repeated execution. Through timer tasks, Spring framework provide support for executing tasks which are scheduled to get executed periodically for multiple times or even single time also.

There are other ways to achieve scheduler functionality in java e.g. running thread in infinite loop, using executor service, or using 3rd party APIs like quartz. Timer just happens to be one of them.

Please note that Timer is dependent on system clock so setting back system clock by n hours, would prevent the next execution of timer task also by n hours.

In Spring, there are two ways to use timer tasks:

  1. Configure MethodInvokingTimerTaskFactoryBean
  2. Extend java.util.TimerTask

Lets demo usage of each one using example.

1. Configure MethodInvokingTimerTaskFactoryBean

In this method, timer task bean and method to be executed inside it, is configured in org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean definition. This is a factory bean which exposes a TimerTask object which delegates job execution to a specified (static or non-static) method. This avoids the need to implement a one-line TimerTask that just invokes an existing business method.

A sample spring configuration will look like this:

<beans>

    <bean id="demoTimerTask" class="com.howtodoinjava.task.DemoTimerTask"></bean>

    <bean id="timerTaskFactoryBean"	
    		class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean">
		<property name="targetObject" ref="demoTimerTask"></property>
		<property name="targetMethod" value="execute"></property>
	</bean>

    <bean id="scheduledTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
		<property name="timerTask" ref="timerTaskFactoryBean"></property>
		<property name="period" value="5000"></property>
	</bean>

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

Above timer task will get executed in every 5 seconds. Lets write out demo timer task and test it.

package com.howtodoinjava.task;

import java.util.Date;

/**
 * No need to implement any interface
 * */
public class DemoTimerTask {

	//Define the method to be called as configured
	public void execute()
	{
		System.out.println("Executed task on :: " + new Date());
	}
}

Now, lets test the timer task.

package com.howtodoinjava.timer;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestDemoTimerTask {
	public static void main(String[] args) {
		new ClassPathXmlApplicationContext("application-config.xml");
	}
}

Executed task on :: Mon Apr 22 09:53:39 IST 2017
Executed task on :: Mon Apr 22 09:53:44 IST 2017

2. Extend java.util.TimerTask

Using this way, we define out timer task by extending java.util.TimerTask and pass it to spring configuration for executing it repeatedly.

Lets see, how to do it:

<beans>

    <bean id="demoTimerTask" class="com.howtodoinjava.task.DemoTimerTask2"></bean>

    <bean id="scheduledTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
	    <!-- run every 3 secs -->
	    <property name="period" value="3000"></property>
	    <property name="timerTask" ref="demoTimerTask"></property>
	</bean>

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

</beans>

Above task will get executed in every 3 seconds. Lets extend out timer task from TimerTask provided by java.

package com.howtodoinjava.task;

import java.util.Date;
import java.util.TimerTask;

public class DemoTimerTask2 extends TimerTask 
{
	public void run() 
	{
		System.out.println("DemoTimerTask2 running at: "
				+ new Date(this.scheduledExecutionTime()));
	}
}

Lets test the configuration:

package com.howtodoinjava.timer;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestDemoTimerTask2 
{
	public static void main(String[] args) 
	{
		new ClassPathXmlApplicationContext("application-config2.xml");
	}
}
DemoTimerTask2 running at: Mon Apr 22 10:01:33 IST 2013
DemoTimerTask2 running at: Mon Apr 22 10:01:36 IST 2013
DemoTimerTask2 running at: Mon Apr 22 10:01:39 IST 2013
Sourcecode Download

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. Thatโ€™s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. sridhar Gadde

    August 31, 2017

    Hi, I Used fixed delay and run the web application, it’s working perfect on the JBOSS server, but recently we moved our web application from JBOSS to tomcat, this scheduler function is not working… is there any suggestion for this.

    • Lokesh Gupta

      August 31, 2017

      Anybody would like to suggest anything??

  2. josh

    October 22, 2015

    simple, straight forward tutorial that I can apply in my work, thanks for this

  3. Prasad

    October 8, 2013

    How can I change the “period” programmatically?

    • Lokesh Gupta

      October 8, 2013

      Try creating an instance of “ScheduledTimerTask” and set the period of your choice. Now try to add this in list of “scheduledTimerTasks”.

      https://docs.spring.io/spring-framework/docs/2.0.x/javadoc-api/org/springframework/scheduling/timer/TimerFactoryBean.html

      Use method: registerTasks(ScheduledTimerTask[] tasks, Timer timer)

      Please let me know if you was able to do it.

  4. hamid samani (@hamid1129)

    April 23, 2013

    yes , but both TimerTask and Spring’s built-in scheduler creates new Thread’s for scheduling and they have same functionality, in addition using spring’s built-in scheduler like Quartz, we can use flexible ‘cron’ expressions for running tasks.

    • Lokesh Gupta

      April 23, 2013

      Your comment inspired me dig more on other ways for task scheduling. I will cover more of them in future posts. But, for now I just posted my learning around @Scheduled annotation in below post:

      https://howtodoinjava.com/spring/spring-core/4-ways-to-schedule-tasks-in-spring-3-scheduled-example/

      • hamid samani (@hamid1129)

        April 23, 2013

        Good , I’m happy for that ๐Ÿ™‚

    • Ohad

      September 30, 2013

      note that in Spring3, “ScheduledTimerTask” is deprecated. The better way to work with timers is like you describe in your other blog post….

  5. hamid samani (@hamid1129)

    April 22, 2013

    I think using @Scheduled annotation is easiest way to execute timer tasks in spring 3.

    • Lokesh Gupta

      April 22, 2013

      Hamid, I doubt that @Scheduled is not used for timer tasks, though it serve the same purpose i.e. executing task periodically.

      Above both techniques use java.util.TimerTask class internally. But in case of @Scheduled, Spring 3’s built-in scheduler just like quartz.

      Please correct me if i am missing anything ??

Comments are closed on this article!

Search Tutorials

Spring Tutorial

  • Spring – Introduction
  • Spring โ€“ IoC Containers
  • Spring – IoC vs. DI
  • Spring – Bean Scopes
  • Spring โ€“ Bean Life Cycle
  • Spring – Bean Postprocessors
  • Spring – Autowiring
  • Spring – Annotations
  • Spring – Stereotype Annotations
  • Spring – Task Scheduling
  • Spring – Timer Task
  • Spring – Events
  • Spring – Message Source
  • Spring – ResourceLoader
  • Spring – Property Editor
  • Spring – Send Email
  • Spring – Version-less Schema
  • Spring – Interview Questions
  • Spring – Best Practices

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces