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

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

2011-05-01 15:41 881 查看
1、定义一个DemoTask类,并继承java.util.TimerTask.

package junit.test;

import java.util.TimerTask;

public class DemoTask extends TimerTask{

public void run(){
System.out.println("Task is excuted:"+System.currentTimeMillis());
}

}
2.在springConfig文件beans-task.xml中配置DemoTask bean定义.

<?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 id="demoTask" class="junit.test.DemoTask" />

</beans>
3.使用Sping的org.springframework.scheduling.timer.ScheduledTimerTask来定义执行周期。

<?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 id="demoTask" class="junit.test.DemoTask" />

<bean id="scheduledTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="timerTask">
<ref bean="demoTask"/>
</property>
<property name="period">
<value>6000</value><!-- 设置间隔时间,毫秒 -->
</property>
<property name="delay">
<value>2000</value><!-- 设置延迟时间开始执行 -->
</property>
</bean>

</beans>
4.使用Spring的org.springframework.scheduling.timer.TimerFactoryBean类来加入所有的任务计划。

<?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 id="demoTask" class="junit.test.DemoTask" />
<bean id="scheduledTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="timerTask">
<ref bean="demoTask"/>
</property>
<property name="period">
<value>6000</value><!-- 设置间隔时间,毫秒 -->
</property>
<property name="delay">
<value>2000</value><!-- 设置延迟时间开始执行 -->
</property>
</bean>

<bean id="timerFactoryBean" class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<ref bean="scheduledTimerTask"/>
</list>
</property>
</bean>
</beans>
到这里,整个beans-task.xml文件配置完成,程序代码也完成,下面我们写个测试方法来测试测试....

package junit.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DemoTaskTestg {

public static void main(String[] args){
new ClassPathXmlApplicationContext("beans-task.xml"); } }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: