首先我们编写调度服务,继承java.util.TimerTask
package
TimerTest;
import
java.util.Date;
import
java.util.TimerTask;

public
class
TimerService
extends
TimerTask
...
{ 
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
可以看到,每隔一秒就打印当前时间的秒数
本文介绍了如何在Spring中使用TimerTask进行调度任务配置。通过编写调度服务并配置相关XML,实现定时任务的执行。在测试代码运行后,观察到每隔一秒即输出当前时间的秒数,验证了定时任务的正确工作。
33

被折叠的 条评论
为什么被折叠?



