1.实现DemoTaskTwo类,该类不在继承java.util.TimerTask.java
package junit.test; public class DemoTaskTwo { public void doSomeThing(){ System.out.println("Task is excuted:"+System.currentTimeMillis()); } }
2.定义SpingConfig 文件beans-task2.xml中的定义spring
<?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"); } }