Wednesday, February 8, 2012

Spring Timer Example

In this blog i will show you how to implement Timer in Spring.

1. Write a Java class with a method which you want to run.
 
package com.msn.spring.scheduling;
  import java.util.Date;

     public class Schedule {
    /*

    This method prints Date
    */

    public void printMessage( ){
        System.out.println(new Date());
        }
 
    }

2. Connfigure this class as a bean in Spring configuration file

 <bean id="scheduler" class="com.msn.spring.scheduling.Schedule" />

3. Configure the following beans with the details like which method to call, and the time period
   
    <bean id="schedulerTask"
 class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean">
    <property name="targetObject" ref="scheduler" />
    <property name="targetMethod" value="printMessage" />
</bean> 

<bean id="timerTask"
    class="org.springframework.scheduling.timer.ScheduledTimerTask">
    <property name="timerTask" ref="schedulerTask" />
    <property name="period" value="1000" /><!--  Here i have configures period property with 1000 mill seconds. So printMessage( ) wiill be called every 1 sec -->
</bean>

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


4. Write a test class which loads the spring configuration file

Test.java
-----------
package com.msn.spring.scheduling;

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

/**
 *
 * @author Naidu */
public class Test {
    public static void main(String[] args){
        ApplicationContext ctx = new ClassPathXmlApplicationContext("com/msn/spring/scheduling/scheduleContext.xml");       
     }
   
}





ScheduleContext.xml
----------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

  <beans>       

<bean id="scheduler" class="com.msn.spring.scheduling.Schedule" />
 <bean id="schedulerTask"
  class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean">
    <property name="targetObject" ref="scheduler" />
    <property name="targetMethod" value="printMessage" />
</bean> 
<bean id="timerTask"
    class="org.springframework.scheduling.timer.ScheduledTimerTask">
    <property name="timerTask" ref="schedulerTask" />
    <property name="period" value="1000" />
</bean>
<bean class="org.springframework.scheduling.timer.TimerFactoryBean">
    <property name="scheduledTimerTasks">
        <list>
            <ref local="timerTask" />
        </list>
    </property>
</bean>

  </beans>






When i run the Test class, printMessage( ) will start executing every one second.







 

No comments:

Post a Comment