spring对Timer(定时器)提供的支

来源:互联网 发布:海康网络摄像机重量 编辑:程序博客网 时间:2024/06/05 04:23

在做系统的时候,为了监听某个状态需要使用“监听器”,即每隔多长时间去“查询”一次,下面介绍的是spring对TimerTask接口的封装类

 

1、配置属性

<!-- 定义实现TimerTask接口的类  -->        <bean id="myTimerTask" class="hb.timer.MyTimerTarsk"></bean>        <!-- 定义spring自带类 ScheduledTimerTask,并将实现TimerTask的接口的类作为属性注入-->        <bean id="stTarsk" class="org.springframework.scheduling.timer.ScheduledTimerTask">        <!-- 首次执行任务需要等待5秒  -->        <property name="delay" value="5000"></property>        <!-- 每隔两秒执行一次 -->        <property name="period" value="2000"></property>        <!-- 该属性对象继承了TimerTask接口,实现了run()方法 -->        <property name="timerTask" ref="myTimerTask"></property>        </bean>        <!-- 定义TimerFactoryBean,该类可以实现同时产生多个ScheduledTimerTask对象 -->        <bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean">        <property name="scheduledTimerTasks">        <list>        <ref local="stTarsk"/>        </list>        </property>        </bean>

 

2、实现TimerTask接口的实现方法

 

package hb.timer;import java.util.TimerTask;public class MyTimerTarsk extends TimerTask {@Overridepublic void run() {System.out.println("1111111");}}

 

3、测试类

package hb.scheduledTimerTask;import java.util.Timer;import org.springframework.context.ApplicationContext;import org.springframework.context.support.FileSystemXmlApplicationContext;public class ScheduledTimerTaskTest {public static void main(String[] args)throws Exception {ApplicationContext ctx = new FileSystemXmlApplicationContext("applicationContext.xml");Timer t = (Timer)ctx.getBean("timerFactory");}}
 

 

原创粉丝点击