Spring使用TimerTask配置调度事务
首先我们编写调度服务,继承java.util.TimerTask
package TimerTest;
import java.util.Date;
import java.util.TimerTask;

public class TimerService extends TimerTask ...{ (文章来源 www.iocblog.net)
public void run() ...{
System.out.println(new Date().getSeconds());
}
}
配置文件:
<?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="reportTask" class="TimerTest.TimerService"/>
<!-- 配置定时器任务 -->
<bean id="scheduledReportTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="timerTask">
<ref bean="reportTask"/>
</property>
<property name="period">
<value>1000</value>
</property>
</bean>
<!-- 启动定时器 -->
<bean id="start" class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<ref bean="scheduledReportTask"/>
</list>
</property>
</bean>
</beans>

测试代码:
package TimerTest;
import java.io.File;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;




public class TestTimer ...{

public static void main(String[] args) ...{
String filePath=System.getProperty("user.dir")+File.separator+"TimerTest"+File.separator+"hello.xml";
ApplicationContext context=new FileSystemXmlApplicationContext(filePath);
//如果使用BeanFactory,则必须调用factory.getBean("start"),才能启动调度任务


}
}
运行结果:
2007-6-5 23:16:24 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.FileSystemXmlApplicationContext@109a4c: display name [org.springframework.context.support.FileSystemXmlApplicationContext@109a4c]; startup date [Tue Jun 05 23:16:24 CST 2007]; root of context hierarchy
2007-6-5 23:16:24 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from file [E:\项目\SpringInActionStudy\TimerTest\hello.xml]
2007-6-5 23:16:24 org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
信息: Bean factory for application context [org.springframework.context.support.FileSystemXmlApplicationContext@109a4c]: org.springframework.beans.factory.support.DefaultListableBeanFactory@cd2c3c
2007-6-5 23:16:24 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@cd2c3c: defining beans [reportTask,scheduledReportTask,start]; root of factory hierarchy
2007-6-5 23:16:24 org.springframework.scheduling.timer.TimerFactoryBean afterPropertiesSet
信息: Initializing Timer
25
26
27
(文章来源 www.iocblog.net)
可以看到,每隔一秒就打印当前时间的秒数
文章整理:iocblog
版权申明:本站文章均来自网络,如有侵权,请联系我们,我们收到后立即删除,谢谢!
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有。