首页 > 解决方案 > 如何重新启动已停止的 Spring Batch 作业

问题描述

@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)
    }

停止工作工作正常,但恢复工作只是在运行项目后第一次工作,如果我再次调用这个方法,我得到这个执行

org.springframework.batch.core.configuration.DuplicateJobException:已注册具有此名称 [LoadData] 的作业配置

任何解决方案!

标签: springspring-batch

解决方案


这是因为您jobRegistry.register(new ReferenceJobFactory(job));每次都在方法内部调用restart,而这通常只调用一次。

因此,您需要从方法中删除该调用,如下所示:

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

并将作业注册移动到在您的 Web 控制器初始化时仅调用一次的方法,例如通过使用带有注释的方法@PostConstruct或使您的控制器实现InitializingBean#afterPropertiesSet. 这是带有@PostConstruct注释的示例:

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

推荐阅读