Spring Batch: Restart A Failed Batch Job Using an API Endpoint

Spring Batch: Restart A Failed Batch Job Using an API Endpoint

An key thing to remember in Spring Batch is that an instance of a Spring Batch job can only be restarted if it FAILED. If the job completeds SUCCESSFULLY a new instance of the job will have to be created to run it again.

When restarting batch jobs manually, is helpful to create an API endpoint for restarting failed batch jobs.

When a batch job is run the first time, it is assigned a batch_job_instance_id and a batch_job_execution_id.

If the job fails and you restart it, it retains the original batch_job_instance_id but receives a new batch_job_execution_id for each subsequent run.

So to restart the job you need to pass the job_execution_id of the failed attempt to a JobOperator.restart() method.

Example


@EnableBatchProcessing // This annotation can be enabled anywhere in the application
@RestController
public class Restart {

    @Autowired
    SimpleJobOperator jobOperator;

    @Autowired
    JobRegistry jobRegistry;

    @Bean // Configure this manually
    public JobRegistryBeanPostProcessor jobRegistryBeanPostProcessor() {
        JobRegistryBeanPostProcessor postProcessor = new JobRegistryBeanPostProcess();
        postProcessor.setJobRegistry(jobRegistry);
        return postProcessor;
    }

    @GetMapping(path = "/restart/{id}")
    public long restartJob(@PathVariable long batchExecutionId) {
        return jobOperator.restart(batchExecutionId);
    }
}