原文地址:http://blog.sina.com.cn/s/blog_4cd3174a01000av7.html
程序不一定要继承TimerTask 那我们也可以使用spring提供的"org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean"类来进行处理了
package onlyfun.caterpillar;
import java.util.TimerTask;
public class DemoTask{
public void execute(){
System.out.println("Task is executed");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="demoTask" class="onlyfun.caterpillar.DemoTask"></bean>
<bean id="timerTaskBean" class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean">
<property name="targetObject">
<ref bean="demoTask"/>
</property>
<property name="targetMethod">
<value>execute</value>
</property>
</bean>
<bean id="scheduledTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="timerTask">
<ref bean="timerTaskBean"></ref>
</property>
<!--这里定义每1秒钟程序执行一次-->
<property name="period">
<value>1000</value>
</property>
<!--这里定义程序启动5秒钟后开始执行-->
<property name="delay">
<value>5000</value>
</property>
</bean>
<bean id="timerFactoryBean" class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<ref bean="scheduledTimerTask"/>
</list>
</property>
</bean>
</beans>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="demoTask" class="onlyfun.caterpillar.DemoTask"></bean>
<bean id="timerTaskBean" class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean">
<property name="targetObject">
<ref bean="demoTask"/>
</property>
<property name="targetMethod">
<value>execute</value>
</property>
</bean>
<bean id="scheduledTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="timerTask">
<ref bean="timerTaskBean"></ref>
</property>
<!--这里定义每1秒钟程序执行一次-->
<property name="period">
<value>1000</value>
</property>
<!--这里定义程序启动5秒钟后开始执行-->
<property name="delay">
<value>5000</value>
</property>
</bean>
<bean id="timerFactoryBean" class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<ref bean="scheduledTimerTask"/>
</list>
</property>
</bean>
</beans>
转载于:https://blog.51cto.com/flymanhi/998517