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

使用Spring来实现任务计划服务二:不继承java.util.TimerTask

2011-05-01 16:38 701 查看
1.实现DemoTaskTwo类,该类不在继承java.util.TimerTask.

package junit.test;

public class DemoTaskTwo {

public void doSomeThing(){

System.out.println("Task is excuted:"+System.currentTimeMillis());

}

}

2.定义SpingConfig 文件beans-task2.xml中的定义

<?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.5.xsd"> <!-- 定义业务逻辑类的bean -->
<bean id="demoTask" class="junit.test.DemoTaskTwo" />
<!-- 通过MethodInvokingTimerTaskFactoryBean 指定业务逻辑bean及方法 -->
<bean id="timerTaskBean" class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean">
<property name="targetObject">
<ref bean="demoTask"/>
</property>
<property name="targetMethod">
<value>doSomeThing</value>
</property>
</bean>
<!-- 通过Spring中的ScheduledTimerTask类来定义执行周期 -->
<bean id="scheduledTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="timerTask">
<ref bean="timerTaskBean"/>
</property>
<property name="period">
<value>6000</value>
</property>
<property name="delay">
<value>3000</value>
</property>
</bean>
<!-- 使用Spring 的TimerFactoryBean类来加入所有的执行计划 -->
<bean id="timerFactoryBean" class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<ref bean="scheduledTimerTask"/>
<!-- 可以加入多个执行计划 -->
</list>
</property>
</bean>

</beans>
3.下面我们写个测试方法来调试一下。

package junit.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DemoTaskTestg {

public static void main(String[] args){
new ClassPathXmlApplicationContext("beans-task2.xml");
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: