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

一、定義一個DemoTask類,並繼承java.util.TimerTask.java

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");	} }
相關文章
相關標籤/搜索