使用Spring來實現任務計劃服務二:不繼承java.util.TimerTask

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


}
相關文章
相關標籤/搜索