要定义一个排程任务(Task),您可以继承 java.util.TimerTask 类别,例如:
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 来定 义任务的执行周期,例如:
<?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 容器启动读取完定义档,就会开始进行所排定的任务,例如:
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 分钟执行一次 任务。