http://www.mkyong.com/spring/spring-jdk-timer-scheduler-example/
In this example, you'll use the Spring ' s Scheduler API to schedule a task.
1. Scheduler Task
Create A Scheduler task ...
Package Com.mkyong.common; public class Runmetask{public void PrintMe () {System.out.println ("Run Me ~");}}
<bean id= "Runmetask" class= "Com.mkyong.common.RunMeTask"/>
Spring comes with a Methodinvokingtimertaskfactorybean as a replacement for the JDK TimerTask. You can define your target scheduler object and method.
<bean id= "Schedulertask" class= "Org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean" ><property name= "TargetObject" ref= "Runmetask"/><property name= "Targetmethod" value= "PrintMe"/>< /bean>
Spring comes with a scheduledtimertask as a replacement for the JDK Timer. You can pass your scheduler name, delay and period here.
<bean id= "TimerTask" class= "Org.springframework.scheduling.timer.ScheduledTimerTask" ><property name= " TimerTask "ref=" Schedulertask "/><property name=" delay "value=" $ "/><property name=" period "value=" 60000 "/></bean>
2. Timerfactorybean
In the last, you can configure a Timerfactorybean beans to start your scheduler task.
<bean class= "Org.springframework.scheduling.timer.TimerFactoryBean" ><property name= "scheduledtimertasks "><list><ref local=" TimerTask "/></list></property></bean>
File:spring-scheduler.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/beanshttp:// Www.springframework.org/schema/beans/spring-beans-2.5.xsd "> <bean id=" Schedulertask "class=" Org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean "><property name=" TargetObject "ref = "Runmetask"/><property name= "Targetmethod" value= "printMe"/></bean> <bean id= "RunMeTask" class= "Com.mkyong.common.RunMeTask"/> <bean id= "TimerTask" class= " Org.springframework.scheduling.timer.ScheduledTimerTask "><property name=" TimerTask "ref=" Schedulertask "/ ><property name= "delay" value= "" "/><property name=" period "value=" 60000 "/></bean> <bean class= "Org.springframework.scheduling.timer.TimerFactoryBean" ><property name= "scheduledtimertasks "><list><ref local=" TimerTask "/></list></propeRty></bean> </beans>
Run it
Package Com.mkyong.common; Import Org.springframework.context.applicationcontext;import Org.springframework.context.support.ClassPathXmlApplicationContext; public class App {public static void Main (string[] args) { ApplicationContext context = new CLASSPATHXM Lapplicationcontext ("Spring-scheduler.xml");} }
No code need to call the scheduler task, the Timerfactorybean would run your schedule task during start up. As result, Spring Scheduler would run the PrintMe () method every seconds, with a 1 second delay for the first time of ex Ecution.
Spring + JDK Timer Scheduler example--reference