Exemple Spring Batch Spring TaskScheduler

Exemple Spring Batch + Spring TaskScheduler

Dans ce didacticiel, nous allons vous montrer comment utiliserSpring TaskScheduler pour planifier une tâche par lots à exécuter toutes les 5 secondes.

Outils et bibliothèques utilisés

  1. Maven 3

  2. Eclipse 4.2

  3. JDK 1.6

  4. Spring Core 3.2.2.RELEASE

  5. Spring Batch 2.2.0.RELEASE

1. Structure du répertoire du projet

Un projet Maven standard.

spring-batch-taskscheduler

2. Planificateur de tâches de printemps

Spring 3.0 introduit unTaskScheduler pour la planification des tâches. Cela fait partie du Spring-Core, pas besoin de déclarer une dépendance supplémentaire.

  
    
  

  
    
  

LesTaskScheduler seront programmés pour s'exécuter sous le bean.

RunScheduler.java

package com.example;

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 need to be unique each time a batch job to run, for testing purpose, we just pass in a new Date() everything running the job.

3. Emplois Spring Batch

Ce travail consiste simplement à lire un fichier csv et à afficher la valeur via un rédacteur personnalisé. Reportez-vous à la fin du fichier, nous utilisonstask:scheduled-tasks pour exécuter ce travail par lots toutes les 5 secondes.

resources/spring/batch/jobs/job-report.xml



  

  
  
    
  

  

  
    
  
  

  

  

  
    
      
        
        
      
    
   

  

    
    

    
      
        
          
            
          
        
        
          
            
          
        
      
    

  

  

  
  
    
    
   

report.csv

1,"139,237"
2,"500,657"
3,"342,100"

CustomWriter.java

package com.example.writers;

import java.util.List;
import org.springframework.batch.item.ItemWriter;
import com.example.model.Report;

public class CustomWriter implements ItemWriter {

  @Override
  public void write(List items) throws Exception {

    System.out.println("writer..." + items.size());
    for(Report item : items){
        System.out.println(item);
    }

  }

}

4. Exécuter

Charge le contexte de l'application Spring, le planificateur sera exécuté automatiquement.

App.java

package com.example;

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

  }
}

En sortie, il imprime le contenu csv toutes les 5 secondes.

......
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]
......

Télécharger le code source

Téléchargez-le -SpringBatch-TaskScheduler-Example.zip (18 ko)