Spring Batch + Spring TaskScheduler示例

本教程展示了如何配置Spring TaskScheduler以每5秒执行一次Spring Batch批处理作业。项目基于Maven,使用Spring Core 3.2.2和Spring Batch 2.2.0。批处理作业从CSV文件读取数据,并通过自定义写入器显示内容。完成设置后,调度程序将在加载Spring应用上下文时自动运行作业。
摘要由CSDN通过智能技术生成

在本教程中,我们将向您展示如何使用Spring TaskScheduler安排每5秒运行一次批处理作业。

使用的工具和库

  1. Maven 3
  2. Eclipse 4.2
  3. JDK 1.6
  4. Spring Core 3.2.2。发布
  5. Spring Batch 2.2.0。发布

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();
    }

  }
}

每次运行批处理作业时,PS JobParamater都必须是唯一的,出于测试目的,我们只需将运行该作业的所有内容传递给new Date()

3.Spring批作业

这项工作只是读取csv文件并通过自定义编写器显示值。 参考文件末尾,我们使用task:scheduled-tasks每5秒运行一次批处理作业。

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);

  }
}

输出,它每5秒钟打印一次csv内容。

......
Sun Jul 28 11:20:30 MYT 2013
Jul 28, 2013 11:20:30 AM org.springframework.batch.core.launch.support.SimpleJobLauncher$1 run
INFO: Job: [FlowJob: [name=reportJob]] launched with the following parameters: [{date=Sun Jul 28 11:20:30 MYT 2013}]
Jul 28, 2013 11:20:30 AM org.springframework.batch.core.job.SimpleStepHandler handleStep
INFO: Executing step: [step1]
writer...3
Report [id=1, Impressions=139,237]
Report [id=2, Impressions=500,657]
Report [id=3, Impressions=342,100]
Jul 28, 2013 11:20:30 AM org.springframework.batch.core.launch.support.SimpleJobLauncher$1 run
INFO: Job: [FlowJob: [name=reportJob]] completed with the following parameters: [{date=Sun Jul 28 11:20:30 MYT 2013}] and the following status: [COMPLETED]
Exit Status : COMPLETED

Sun Jul 28 11:20:35 MYT 2013
Jul 28, 2013 11:20:35 AM org.springframework.batch.core.launch.support.SimpleJobLauncher$1 run
INFO: Job: [FlowJob: [name=reportJob]] launched with the following parameters: [{date=Sun Jul 28 11:20:35 MYT 2013}]
Jul 28, 2013 11:20:35 AM org.springframework.batch.core.job.SimpleStepHandler handleStep
INFO: Executing step: [step1]
writer...3
Report [id=1, Impressions=139,237]
Report [id=2, Impressions=500,657]
Report [id=3, Impressions=342,100]
Exit Status : COMPLETED
Jul 28, 2013 11:20:35 AM org.springframework.batch.core.launch.support.SimpleJobLauncher$1 run
INFO: Job: [FlowJob: [name=reportJob]] completed with the following parameters: [{date=Sun Jul 28 11:20:35 MYT 2013}] and the following status: [COMPLETED]
......

下载源代码

下载它– SpringBatch-TaskScheduler-Example.zip (18 kb)

参考文献

  1. Spring– Schedululing一个任务。
  2. 维基:Cron

翻译自: https://mkyong.com/spring-batch/spring-batch-and-spring-taskscheduler-example/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值