Spring Batch: une instance de travail existe déjà et est terminée pour parameters = \ {}

Spring Batch: une instance de travail existe déjà et est terminée pour les paramètres = \ {}

Travailler avec Spring Batch 2.2.0.RELEASE et lance le travail avec Spring Scheduler.

CustomJobLauncher.java

package com.example.batch;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CustomJobLauncher {

    @Autowired
    JobLauncher jobLauncher;

    @Autowired
    Job job;

    public void run() {

      try {

        JobExecution execution = jobLauncher.run(job, new JobParameters());
        System.out.println("Exit Status : " + execution.getStatus());

      } catch (Exception e) {
        e.printStackTrace();
      }

    }

}

job-config.xml

  

  
    
  

Problème

Le travail par lots s'exécute avec succès la première fois uniquement, lorsqu'il se lance la deuxième fois (après 10 secondes), il affiche les messages d'erreur suivants.

org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException:
    A job instance already exists and is complete for parameters={}.
        If you want to run this job again, change the parameters.
    at org.springframework.batch.core.repository.support.SimpleJobRepository.createJobExecution(SimpleJobRepository.java:126)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

Solution

Reportez-vous au message d'erreur ci-dessus «If you want to run this job again, change the parameters.». La formule estJobInstance = JobParameters + Job. Si vous n'avez aucun paramètre pourJobParameters, passez simplement une heure courante comme paramètre pour créer un nouveauJobInstance. Par exemple,

CustomJobLauncher.java

//...

@Component
public class CustomJobLauncher {

    @Autowired
    JobLauncher jobLauncher;

    @Autowired
    Job job;

    public void run() {

      try {
        JobParameters jobParameters =
          new JobParametersBuilder()
          .addLong("time",System.currentTimeMillis()).toJobParameters();

        JobExecution execution = jobLauncher.run(job, jobParameters);
        System.out.println("Exit Status : " + execution.getStatus());

      } catch (Exception e) {
        e.printStackTrace();
      }

    }

}