您的位置:首页 > 编程语言 > Java开发

Spring定时任务的实现方式--Timer和TimerTask

2016-11-03 17:00 309 查看
Timer实际上是个线程,它可以定时调度一个TimerTask对象。一个TimerTask实际上就是一个拥有run方法的类,需要定时执行的代码放到run方法体内。 

方式一:使用配置文件

1.写一个类,实现定时任务:

package com.Solin.Timer;

import java.util.Date;
import java.util.TimerTask;

public class TestTimerTask extends TimerTask{

@Override
public void run() {
System.out.println(new Date()+" TimerTask...");
}

}


2.Spring配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 
<bean id="testTimerTask" class="com.Solin.Timer.TestTimerTask"></bean>
<bean id="scheduledTestTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="delay" value="2000" />
<property name="period" value="30000" />
<property name="timerTask" ref="testTimerTask" />
</bean>
<bean class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<ref bean="scheduledTestTimerTask" />
</list>
</property>
</bean>
</beans>
以上配置文件的详细解释:

"testTimerTask"这个Bean定义了定时器任务。

下面的代码是从Spring框架中声明定时器任务的调度对象:

<bean id="scheduledTestTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="delay" value="2000" />
<property name="period" value="30000" />
<property name="timerTask" ref="testTimerTask" />
</bean>
org.springframework.scheduling.timer.ScheduledTimerTask这个类提供了对定时任务调度执行的支持。

属性delay的单位是毫秒,它指定任务执行前需要延时多少时间。2000意味着延时2秒开始执行任务。

第二个属性period的单位也是毫秒,它表示任务每隔多少时间就重复执行一次。30000这个值表示每隔30秒执行一次。

最后一个属性是timerTask,它指定实际要执行的任务。

触发调度任务是通过TimerFactoryBean进行的。它可以指定待调度的任务对象列表,尽管这里只有1个待调度的任务对象。
<bean class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<ref bean="scheduledTestTimerTask" />
</list>
</property>
</bean>

 

3.启动项目后,控制台会打印如下信息:

Thu Nov 03 17:28:42 CST 2016 TimerTask...
Thu Nov 03 17:29:12 CST 2016 TimerTask...
Thu Nov 03 17:29:42 CST 2016 TimerTask...
Thu Nov 03 17:30:12 CST 2016 TimerTask...
Thu Nov 03 17:30:42 CST 2016 TimerTask...


方式二:不使用配置文件

具体使用方法见:http://blog.csdn.net/qq_32786873/article/details/53005976
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐