I am trying to simulate the scenario where, doing a Thread.sleep() in the reader, yet even if the current running job does not complete another job gets submitted to thread pool, how do i prevent this from happening?
@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;
}```
You can find the running conditions of the job if in case you start the job with same job name.
Based on the running conditions you can build your system whether or not to start a new job.
We need to autowire JobExplorer,
@Autowired
JobExplorer jobExplorer;
Method snippet for your reference,
for (JobExecution jobExecution : jobExecutionsSet) {
if (jobExecution.getStatus() != BatchStatus.STARTED || jobExecution.getStatus() != BatchStatus.STARTING) {
// start the new job
} else {
// prevent it from starting
}
}