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

《pro Spring》学习笔记之使用JDK Timer调度任意任务

2007-09-10 23:52 513 查看
Spring对Timer的支持核心是由ScheduledTimerTask和TimerFactoryBean类组成,前者扮演后者一个wrapper的角色,通过 TimerFactoryBean,你能够让Spring使用配置创建触发器,为一指定的ScheduledTimerTask bean自动创建Timer实例

我们一般可以编写TimerTask的类,或者ScheduledTimerTas类的子类,实现其run或者getDelay方法来完成具体的定时任务,但是,基于POJ的设计原则,我们希望对一个普通的java中的方法,进行调度,该如何处理呢,请看以下代码



POJO:




package ch14.AnyTimerTask;




import java.util.TimerTask;






import java.util.TimerTask;






public class HelloWorldTask ...{




public void someJob(String message) ...{


System.out.println(message);




}




}









配置文件

核心是MethodInvokingTimerTaskFactoryBean




<?xml version="1.0" encoding="UTF-8"?>


<beans


xmlns="http://www.springframework.org/schema/beans"


xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"


xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">



<bean id="target" class="ch14.AnyTimerTask.HelloWorldTask">


</bean>




<bean id="task" class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean">


<property name="targetObject">


<ref bean="target"/>


</property>


<property name="targetMethod">


<value>someJob</value>


</property>


<property name="arguments">


<value>hello world 3q!</value>


</property>


</bean>




<bean id="timerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">


<property name="delay">


<value>1000</value>


</property>


<property name="period">


<value>2000</value>


</property>


<property name="timerTask">


<ref bean="task"/>


</property>


</bean>




<bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean">


<property name="scheduledTimerTasks">


<ref bean="timerTask"/>


</property>


</bean>


</beans>



测试代码:




package ch14.AnyTimerTask;




import org.springframework.context.ApplicationContext;


import org.springframework.context.support.ClassPathXmlApplicationContext;






public class Test ...{






/** *//**


* @param args


*/




public static void main(String[] args) throws Exception...{


ApplicationContext context=new ClassPathXmlApplicationContext("ch14/AnyTimerTask/applicationContext.xml");


System.in.read();







}




}





运后可以看到,延迟1000毫秒后,每个2000毫秒便运行一次somJob方法,其中我们用arguments参数定义了方法的参数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: