Spring批量仅限制单个作业实例

san*_*eep 8 java spring-batch

我有一个春季批处理作业,可以通过休息URL踢.我想确保只允许一个作业实例运行.如果另一个实例已经运行,那么不要启动另一个 即使参数不同.

我搜查了一下,没有找到任何解决方案.考虑扩展SimpleJobLauncher.检查作业的任何实例是否正在运行.

Tom*_*ros 6

您可以尝试拦截作业执行,实现JobExecutionListener接口:

public class MyJobExecutionListener extends JobExecutionListener {

    //active JobExecution, used as a lock.
    private JobExecution _active;

    public void beforeJob(JobExecution jobExecution) {
        //create a lock
        synchronized(jobExecution) {
            if(_active!=null && _active.isRunning()) {
                jobExecution.stop();
            } else {
                _active=jobExecution;
            }
        }
    }

    public void afterJob(JobExecution jobExecution) {
          //release the lock
          synchronized(jobExecution) {
              if(jobExecution==_active) {
                _active=null; 
              }
          }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,注入Job定义:

<job id="myJobConfig">
    <listeners>
        <listener ref="myListener"/>
    </listeners>
</job>
Run Code Online (Sandbox Code Playgroud)


san*_*eep 5

我通过创建 JobExecutionListner 解决了这个问题,在 JobExplorer 的帮助下,我检查了是否有任何其他实例正在运行,如果正在运行,然后停止当前作业。我创建了侦听器,以便它可以插入任何需要这种场景的作业。

Set<JobExecution> jobExecutions = ((SimpleJobExplorer) jobExplorer.getObject()).findRunningJobExecutions(jobExecution.getJobInstance().getJobName());
            if(jobExecutions.size()>1){
                Long currentTime = (new Date()).getTime();
                for(JobExecution execution : jobExecutions ){
                    if(execution.getJobInstance().getId().compareTo(jobExecution.getJobInstance().getId())!=0 && (currentTime - execution.getStartTime().getTime()) <lockOverideTime){
                        jobExecution.stop();
                        throw new IllegalStateException("Another instance of the job running job name : " +jobExecution.getJobInstance().getJobName() );

                    }
                }

            }
Run Code Online (Sandbox Code Playgroud)