I had been implemented a Timer tool using Swing to schedule the task to batch the bank transaction. Then last year I did work with a project to do the same thing but used Spring framework’s Timer. The more step is to allow user change the interval time
after Spring configuration has been loaded. Here is my approach.

1. Build the fundamental Spring Timer
Spring: Scheduling and Thread Pooling ( In this case I choose JDK Timer.)

2. Modify your Task to implement org.springframework.beans.factory.InitializingBean
This class will override afterPropertiesSet() method to change your interval time.

3. FYI: EJB 3.0 Timer

4. Code snippest

applicationContext.xml
<!– java.util.Timer + spring integration –>
<bean id=”myWorkTask” class=”com.me.MyEventTask”>
<property name=”insiderService”><ref local=”insiderService”/></property>
</bean>

<bean id=”jobDetail” class=”org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean”>
<property name=”targetObject” ref=”myWorkTask”/>
<property name=”targetMethod” value=”doIt”/>
</bean>

<bean id=”myScheduledTask” class=”com.me.MyScheduledTask”>
<!– wait 30 mins before starting repeated execution –>
<property name=”delay” value=”1800000″/>
<!– run every 60 mins , if you input -1, then it only runs once. –>
<property name=”period” value=”3600000″/>
<property name=”timerTask” ref=”jobDetail”/>
</bean>

<bean id=”timeFactory” class=”org.springframework.scheduling.timer.TimerFactoryBean”>
<property name=”myAllTasks”>
<list>
<ref bean=”myScheduledTask”/>
</list>
</property>
</bean>

package com.me;import org.springframework.beans.factory.InitializingBean;

import java.io.InputStream;

import java.util.Properties;

public class MyScheduledTask extends org.springframework.scheduling.timer.ScheduledTimerTask implements InitializingBean {

 private props = null;

public MyScheduledTask(){

         Properties props = new Properties();

         /**

          * process.properties loads

          */

         InputStream is = getClass().getResourceAsStream("/resources/myparas.properties");

        	props.load(is);

 }

public void afterPropertiesSet() throws Exception {

 	//read parameter from properties file or from database

 	String param = props.getProperty("INTERVAL");

 	long sysInterval = Long.valueOf(param).longValue()*1000;

 	if(sysInterval != 0){

 		//this method will change the value of timer interval time.

 		setPeriod(sysInterval);

 	}

 }

}
Advertisements