使用TimerTask


要定義一個排程任務(Task),您可以繼承java.util.TimerTask類別,例如:
  • DemoTask.java
package onlyfun.caterpillar;

import java.util.TimerTask;

public class DemoTask extends TimerTask {
public void run() {
System.out.println("Task is executed.");
}
}

接著您可以使用Spring的org.springframework.scheduling.timer.ScheduledTimerTask來定義任務的執行週期,例如:
  • beans-config.xml
<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<bean id="demoTask"
class="onlyfun.caterpillar.DemoTask"/>

<bean id="scheduledTimerTask"
class="org.springframework.scheduling.
→ timer.ScheduledTimerTask">
<property name="timerTask">
<ref bean="demoTask"/>
</property>
<property name="period">
<value>600000</value>
</property>
<property name="delay">
<value>10000</value>
</property>
</bean>

<bean id="timerFactoryBean"
class="org.springframework.scheduling.
→ timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<ref bean="scheduledTimerTask"/>
</list>
</property>
</bean>
</beans>

在ScheduledTimerTask類別的"period"屬性中,定義的單位是毫秒,因此根據以上的定義中,將每10分鐘執行一次所定義的任務,而"delay"屬性定義了Timer啟動後,第一次執行任務前要延遲多少毫秒。

定義好的ScheduledTimerTask要使用 org.springframework.scheduling.timer.TimerFactoryBean類別來加入所有的排程任務,接下來只要 Spring容器啟動讀取完定義檔,就會開始進行所排定的任務,例如:
  • TimerTaskDemo.java
package onlyfun.caterpillar;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.springframework.context.
support.FileSystemXmlApplicationContext;

public class TimerTaskDemo {
public static void main(String[] args) throws IOException {
new FileSystemXmlApplicationContext("beans-config.xml");
System.out.println("啟動 Task..");
System.out.println("請輸入 exit 關閉 Task: ");

BufferedReader reader =
new BufferedReader(
new InputStreamReader(System.in));

while(true) {
if(reader.readLine().equals("exit")) {
System.exit(0);
}
}
}
}

根據Bean定義檔的內容,這個程式在啟動後10秒會執行第一次任務,之後每10分鐘執行一次任務。