javaspringspring-batchspring-cloud-task

JobRestartException: JobInstance already exists and is not restartable


I'm using Spring Batch with Spring cloud tasks. I have the following configuration in my job:

@Bean
    public Job jobDemo(
            @Value("${jobname}")String jobName,
            JobBuilderFactory jobBuilderFactory,
            JobCompletionNotificationListener listener
        ) {
        return jobBuilderFactory.get(jobName)
                .incrementer(new RunIdIncrementer())
                .preventRestart()
                .listener(listener)
                .flow(stepA())
                .end()
                .build();
    }

I don't want the restart functionality in the job, that's why I have put .preventRestart(). I want to launch a new job every time the task runs, that is, a new instance of the job to run even when the last time the job has failed or stopped or anything. But I'm getting the following error:

org.springframework.batch.core.repository.JobRestartException: JobInstance already exists and is not restartable

This happens only in the scenarios when the job does not finish sucessfully. Any ideas about the solution?


Solution

  • A JobInstance can only be completed once successfully. When you are starting a Spring Batch job via Spring Boot, Spring Batch handles the logic to increment a JobParameter if there is a JobParametersIncrementer provides (as you have). However...when Spring Batch does that incrementing, it only increments if the previous job was successful. In your case, you want it to always increment. Because of that, you're going to need to write your own CommandLineRunner that always increments the JobParameters.

    Spring Boot's JobLauncherCommandLineRunner is where the code to launch a job exists. You'll probably want to extend that and override it's execute method to be sure job parameters are always incremented.