Spring JDKタイマースケジューラの例
この例では、SpringのScheduler APIを使用してタスクをスケジュールします。
1.スケジューラタスク
スケジューラタスクを作成する…
package com.mkyong.common; public class RunMeTask { public void printMe() { System.out.println("Run Me ~"); } }
<bean id="runMeTask" class="com.mkyong.common.RunMeTask"/>
Springには、JDK TimerTaskの代わりに
MethodInvokingTimerTaskFactoryBean
が付属しています。ここで呼び出すターゲットスケジューラオブジェクトとメソッドを定義することができます。
<bean id="schedulerTask" class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean"> <property name="targetObject" ref="runMeTask"/> <property name="targetMethod" value="printMe"/> </bean>
Springには、JDKタイマーの代わりに
ScheduledTimerTask
が付属しています。スケジューラの名前、遅延、期間をここに渡すことができます。
<bean id="timerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask"> <property name="timerTask" ref="schedulerTask"/> <property name="delay" value="1000"/> <property name="period" value="60000"/> </bean>
2. TimerFactoryBean
最後に、TimerFactoryBean Beanを構成して、スケジューラー・タスクを開始することができます。
<bean class="org.springframework.scheduling.timer.TimerFactoryBean"> <property name="scheduledTimerTasks"> <list> <ref local="timerTask"/> </list> </property> </bean>
File:Spring-Scheduler.xml
<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="schedulerTask" class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean"> <property name="targetObject" ref="runMeTask"/> <property name="targetMethod" value="printMe"/> </bean> <bean id="runMeTask" class="com.mkyong.common.RunMeTask"/> <bean id="timerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask"> <property name="timerTask" ref="schedulerTask"/> <property name="delay" value="1000"/> <property name="period" value="60000"/> </bean> <bean class="org.springframework.scheduling.timer.TimerFactoryBean"> <property name="scheduledTimerTasks"> <list> <ref local="timerTask"/> </list> </property> </bean> </beans>
それを実行します
package com.mkyong.common; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main( String[]args ) { ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Scheduler.xml"); } }
-
TimerFactoryBean ** は起動時にスケジュールタスクを実行します。結果として、Springスケジューラは60秒ごとにprintMe()メソッドを実行し、最初の実行では1秒の遅延が発生します。
ソースコードをダウンロードする
ダウンロードする –
Spring-Scheduler-JDK-TimerExample.zip