Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring batch restrict single instance of job across multiple servers

I have one Spring Batch job that can potentially be run across multiple servers. I have a listener in place that prevents multiple instances of the job being run at the same time on one server. However, I want to ensure this job can't be run at the same time on multiple servers.

I've searched and found no solution to this problem

like image 495
Josh Avatar asked Jun 07 '18 16:06

Josh


1 Answers

I implemented a listener that checks the number of running Job Executions within the spring batch control tables matching a certain name. If there size of the executions exceeds 1, jobExecution of the current job fails. Here's the code:

@Component
public class SingleInstanceListener implements JobExecutionListener {
    @Autowired
    private JobExplorer explorer;

    @Override
    public void beforeJob(JobExecution jobExecution) {
        String jobName = jobExecution.getJobInstance().getJobName();
        Set<JobExecution> executions = explorer.findRunningJobExecutions(jobName);
        if(executions.size() > 1) {
            jobExecution.stop();
        }
    }

    @Override
    public void afterJob(JobExecution jobExecution) {

    }

}
like image 53
Josh Avatar answered Sep 28 '22 00:09

Josh