标签:
一、分类
二、Java自带的java.util.Timer类
1.构建线程类
public class MyTask {
private String name;
public void run() {
System.out.println("Run task: " + name + ".");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2.创建spring的配置文件,spring.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"
default-lazy-init="true">
<bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean" lazy-init="false">
<property name="scheduledTimerTasks">
<list>
<ref local="scheduledTask1"/>
</list>
</property>
</bean>
<bean id="scheduledTask1" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="delay" value="0" />
<property name="period" value="10000" />
<property name="timerTask">
<ref bean="methodInvokingTask1"/>
</property>
</bean>
<bean id="methodInvokingTask1" class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean">
<property name="targetObject" ref="myTask1"/>
<property name="targetMethod" value="run"/>
</bean>
<bean id="myTask1" class="org.garbagecan.springstudy.schedule.timer.MyTask">
<property name="name" value="task1"/>
</bean>
</beans>
三、调度说明
1. 定义了一个task,task1。
2. 利用spring提供的MethodInvokingTimerTaskFactoryBean类来实现来实现对对task类和方法的声明,声明目标对象和方法,从而使spring知道要运行那个类的那个方法。
3. 利用ScheduledTimerTask类来配置每个task的启动时间延时,每次启动之间的间隔,当然还有最重要的是需要运行那个对象,这里使用的上面提到的MethodInvokingTimerTaskFactoryBean类 的实例。
4. 最后定义了一个TimerFactoryBean类,并且把ScheduledTimerTask类的实例作为需要调度的task。
四、测试类
package org.garbagecan.springstudy.schedule.timer;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) throws Exception {
new ClassPathXmlApplicationContext("/org/garbagecan/springstudy/schedule/timer/spring.xml");
}
}
运行Test类,可以看到task启动,并且使用每10秒作为每次运行之间的时间
标签:
原文地址:http://www.cnblogs.com/hongwz/p/5642320.html