如何防止在spring batch上,如果前一个作业还在运行,如何防止计划作业的执行?

问题描述 投票:0回答:1

我试图模拟这样的场景:在阅读器中执行Thread.sleep(),但即使当前正在运行的作业没有完成,另一个作业也会被提交到线程池,我如何防止这种情况发生?

@Scheduled(fixedRate = 100)
public void executeChunkJob() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {
    executeJob(chunkJob);
}

private void executeJob(Job jobToRun) throws JobParametersInvalidException, JobExecutionAlreadyRunningException,
        JobRestartException, JobInstanceAlreadyCompleteException{
    try {
        JobParameters parameters = new JobParametersBuilder()
                .addString("JobID", String.valueOf(System.currentTimeMillis())).toJobParameters();

        JobExecution jobExecution = jobLauncher().run(jobToRun, parameters);
        System.out.println("JOb Execution" + jobExecution.getExitStatus());
    } catch(JobExecutionAlreadyRunningException | JobRestartException | JobInstanceAlreadyCompleteException | JobParametersInvalidException e) {
        throw e;
    } catch(OutOfMemoryError | Exception e) {
    }
}

@Bean
public JobLauncher jobLauncher() throws Exception
{
    SimpleJobLauncher jobLauncher = new SimpleJobLauncher();

    jobLauncher.setJobRepository(jobRepository);
    jobLauncher.setTaskExecutor(getCustomTaskExecutor());
    jobLauncher.afterPropertiesSet();

    return jobLauncher;
}

@Bean(name= "myExecutor")
public TaskExecutor getCustomTaskExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(10);
    executor.setMaxPoolSize(100);
    executor.setQueueCapacity(100);
    executor.initialize();
    return executor;
}```
spring-boot spring-batch threadpoolexecutor
1个回答
0
投票

如果你用相同的作业名启动作业,你可以找到作业的运行条件。

根据运行条件,你可以建立你的系统是否启动一个新的作业。

我们需要自动启动JobExplorer。

@Autowired
JobExplorer jobExplorer;

方法片段供您参考。

for (JobExecution jobExecution : jobExecutionsSet) {

   if (jobExecution.getStatus() != BatchStatus.STARTED || jobExecution.getStatus() != BatchStatus.STARTING) {
       // start the new job
   } else {
       // prevent it from starting
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.