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"); } }