首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

spring 对 timer 的支持 兑现简单的web中定时器操作

2012-09-04 
spring 对 timer 的支持 实现简单的web中定时器操作一共分两个步骤:1.写一个java.util.Timer的子类,实现ru

spring 对 timer 的支持 实现简单的web中定时器操作

一共分两个步骤:

1.写一个java.util.Timer的子类,实现run方法。

package com.test;/** * @author Evan */public class TimerTaskSample extends java.util.TimerTask {@Overridepublic void run() {System.out.println("spring is invoking a timer task...");}}

?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:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"> <bean id="timerTask" value="10000"></property><property name="period" value="5000"></property><property name="timerTask" ref="timerTask" ></property></bean><bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean"><property name="scheduledTimerTasks"><list><ref local="scheduledTask"></ref></list></property></bean></beans>

?delay:延时(毫秒) ,过多久后执行timerTask

period:间隔多久(毫秒)执行一次

timerTask:要执行的任务。

?

timerFactory:spring调用任务的工厂,可以指定多个任务。

以上只是一个简单的例子,可以用于在启动web容器后,后台自动定时执行的内容可以增加在Timer子类的run方法中,比如:定时去查询数据库的数据,向其他服务器发消息等。

如果有复杂的需求,可以考虑使用quartz,这个spring也是支持的,暂时没研究。

1 楼 reilost 2010-09-10   。。。。。。。。。。。伟爷威武-。- 2 楼 EvanHuang125 2010-09-13   reilost 写道。。。。。。。。。。。伟爷威武-。-
开发中用到了,写在这里总结下,不然过段时间就忘了,呵呵!

热点排行