how to restart a Stopped Spring Batch job

Viewed 342
@GetMapping("/stopjob")
public void stop() throws Exception{
    Set<Long> executions = jobOperator.getRunningExecutions("LoadData");
    jobOperator.stop(executions.iterator().next());
}


@GetMapping("/resumejob/{id}")
public void restart(@PathVariable(name = "id") long id) throws Exception {
    jobRegistry.register(new ReferenceJobFactory(job));
       jobOperator.restart(id); // (1)
    }

stop a job works fine but resume job works just the first time after running the project and if i invoke this method another time i get this execption

org.springframework.batch.core.configuration.DuplicateJobException: A job configuration with this name [LoadData] was already registered

any solution !

1 Answers

This is because you are calling jobRegistry.register(new ReferenceJobFactory(job)); each time inside the restart method, while this is typically called only once.

So you need to remove that call from the method like this:

@GetMapping("/resumejob/{id}")
public void restart(@PathVariable(name = "id") long id) throws Exception {
   jobOperator.restart(id); // (1)
}

And move the job registration to a method that is called only once when your web controller is initialized, for example by using a method annotated with @PostConstruct or making your controller implement InitializingBean#afterPropertiesSet. Here is an example with the @PostConstruct annotation:

@PostConstruct
public void registerJob() {
   jobRegistry.register(new ReferenceJobFactory(job));
}
Related