spring-batch-使用JobExecutionListener不断重新启动作业



我们需要一个作业来连续运行,而不需要外部调度程序。我扩展了JobExecutionListener,如下所示:

@Autowired
@Qualifier("myJob")
private Job job;
private int counter = 0;
@Override
public void afterJob(JobExecution jobExecution) {
   jobExecution.stop();
   JobParameters jobParameters = new JobParameters();
   JobParameter jobParameter = new JobParameter((new Integer(++counter)).toString());
   jobParameters.getParameters().put("counter", jobParameter);
   try {
      jobLauncher.run(job, jobParameters);
   } 
   catch (JobExecutionAlreadyRunningException e) {
      throw new RuntimeException(e);
   } catch (JobRestartException e) {
      throw new RuntimeException(e);
   } catch (JobInstanceAlreadyCompleteException e) {
      throw new RuntimeException(e);
   } catch (JobParametersInvalidException e) {
      throw new RuntimeException(e);
}

运行时,会引发JobExecutionAlreadyRunningException。

JobExecutionAlreadyRunningException: A job execution for this job is already running: JobInstance: id=0, version=0, Job=[myJob]

我哪里错了?

感谢

来自官方文档:

关闭不是立即的,因为没有办法强制立即关闭,特别是当执行当前处于框架无法控制的开发人员代码,例如商务服务。但是,一旦控制权返回到框架,它会将当前StepExecution的状态设置为批次状态。STOPPED,保存它,然后对JobExecution执行相同操作在完成之前。

也许你可以有机会使用专门的JobLauncher,在上一个作业的线程终止后启动作业,或者使用与JobLauncher关联的自定义TaskExecutor。

最新更新