SpringバッチSpring TaskSchedulerの例
このチュートリアルでは、
Spring TaskScheduler
を使用して5秒ごとにバッチ・ジョブを実行するようにスケジュールする方法を説明します。
使用されるツールとライブラリ
-
Maven 3
-
Eclipse 4.2
-
JDK 1.6
-
Spring Core 3.2.2.RELEASE
-
Spring Batch 2.2.0.RELEASE
1.プロジェクトのディレクトリ構造
標準のMavenプロジェクト。
2. Spring TaskScheduler
Spring 3.0では、タスクをスケジュールするための `TaskScheduler`が導入されています。これはSpring Coreの一部であり、余分な依存関係を宣言する必要はありません。
<task:scheduled-tasks> <task:scheduled ref="runScheduler" method="run" fixed-delay="5000"/> </task:scheduled-tasks> <task:scheduled-tasks> <task:scheduled ref="runScheduler" method="run" cron="** /5 ** ** ** ** ** "/> </task:scheduled-tasks>
`TaskScheduler`はBeanの下で実行するようにスケジュールします。
RunScheduler.java
package com.mkyong; import java.util.Date; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.JobParametersBuilder; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class RunScheduler { @Autowired private JobLauncher jobLauncher; @Autowired private Job job; public void run() { try { String dateParam = new Date().toString(); JobParameters param = new JobParametersBuilder().addString("date", dateParam).toJobParameters(); System.out.println(dateParam); JobExecution execution = jobLauncher.run(job, param); System.out.println("Exit Status : " + execution.getStatus()); } catch (Exception e) { e.printStackTrace(); } } }
__P.S JobParamaterは、バッチジョブを実行するたびに一意である必要があります。テスト目的のために、ジョブを実行するすべての新しいDate()を渡します。
3.バッチバッチジョブ
この仕事はちょうどcsvファイルを読んで、カスタムライターで値を表示しています。このバッチジョブを5秒ごとに実行するには、ファイルの最後を参照して、 `task:scheduled-tasks`を使用します。
resources/spring/batch/jobs/job-report.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:batch="http://www.springframework.org/schema/batch" xmlns:context="http://www.springframework.org/schema/context" xmlns:task="http://www.springframework.org/schema/task" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd "> <context:component-scan base-package="com.mkyong"/> <!-- job context --> <bean id="jobRepository" class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean"> <property name="transactionManager" ref="transactionManager"/> </bean> <bean id="transactionManager" class="org.springframework.batch.support.transaction.ResourcelessTransactionManager"/> <bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher"> <property name="jobRepository" ref="jobRepository"/> </bean> <!-- job context --> <bean id="report" class="com.mkyong.model.Report" scope="prototype"/> <bean id="customWriter" class="com.mkyong.writers.CustomWriter"/> <batch:job id="reportJob"> <batch:step id="step1"> <batch:tasklet> <batch:chunk reader="cvsFileItemReader" writer="customWriter" commit-interval="10"> </batch:chunk> </batch:tasklet> </batch:step> </batch:job> <bean id="cvsFileItemReader" class="org.springframework.batch.item.file.FlatFileItemReader"> <!-- Read a csv file --> <property name="resource" value="classpath:cvs/input/report.csv"/> <property name="lineMapper"> <bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper"> <property name="lineTokenizer"> <bean class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer"> <property name="names" value="id,impressions"/> </bean> </property> <property name="fieldSetMapper"> <bean class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper"> <property name="prototypeBeanName" value="report"/> </bean> </property> </bean> </property> </bean> <bean id="runScheduler" class="com.mkyong.RunScheduler"/> <!-- Run every 5 seconds --> <task:scheduled-tasks> <!-- <task:scheduled ref="runScheduler" method="run" fixed-delay="5000"/> --> <task:scheduled ref="runScheduler" method="run" cron="** /5 ** ** ** ** ** "/> </task:scheduled-tasks> </beans>
report.csv
1,"139,237" 2,"500,657" 3,"342,100"
CustomWriter.java
package com.mkyong.writers; import java.util.List; import org.springframework.batch.item.ItemWriter; import com.mkyong.model.Report; public class CustomWriter implements ItemWriter<Report> { @Override public void write(List<? extends Report> items) throws Exception { System.out.println("writer..." + items.size()); for(Report item : items){ System.out.println(item); } } }
4.それを実行する
Springアプリケーションコンテキストをロードすると、スケジューラが自動的に実行されます。
App.java
package com.mkyong; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main(String[]args) { String springConfig = "spring/batch/jobs/job-report.xml"; ApplicationContext context = new ClassPathXmlApplicationContext(springConfig); } }
出力すると、csvの内容が5秒ごとに出力されます。
...... Sun Jul 28 11:20:30 MYT 2013年7月28日11:20:30 org.springframework.batch.core.launch.support.SimpleJobLauncher $ 1を実行する情報:ジョブ:[FlowJob:[name = reportJob]]次のパラメータ:[{date = Sun Jul 28 11:20:30 MYT 2013}]2013年7月28日11:20:30 org.springframework.batch.core.job.SimpleStepHandler handleStep INFO:ステップ実行:[step1]作者... 3レポート[id = 1、インプレッション= 139,237]レポート[ID = 2、インプレッション= 500,657]レポート[ID = 3、インプレッション= 342,100]2011年7月28日11:20:30 org.springframework.batch .core.launch.support.SimpleJobLauncher $ 1を実行します。INFO:Job:[FlowJob:[name = reportJob]]が[{date = Sun Jul 28 11:20:30 MYT 2013}]のパラメータと次のステータスで完了しました:[COMPLETED]終了ステータス:COMPLETED Sun Jul 28 11:20:35 MYT 2013 2011年7月28日11:20:35 AM org.springframework.batch.core.launch.support.SimpleJobLauncher $ 1が実行されます。 情報:ジョブ:[FlowJob:[name = reportJob]]は、次のパラメータで起動しました:[{date = Sun Jul 28 11:20:35 MYT 2013}]2011年7月28日11時20分35秒org.springframework.batch.core.job.SimpleStepHandler handleStep 情報:実行ステップ:[ステップ1]作家... 3 レポート[id = 1、インプレッション数= 139,237]レポート[id = 2、インプレッション数= 500,657]レポート[id = 3、インプレッション数= 342,100]終了ステータス:完了 2011年7月28日11:20:35 AM org.springframework.batch.core.launch.support.SimpleJobLauncher $ 1が実行されます。 INFO:ジョブ:[FlowJob:[name = reportJob]]は、[{date = Sun Jul 28 11:20:35 MYT 2013}]と次のステータスで完了しました:[COMPLETED]......
ソースコードをダウンロードする
ダウンロードする –
SpringBatch-TaskScheduler-Example.zip
(18 kb)