dReAmEr
dReAmEr

Reputation: 7194

How to create Master Job to process multiple spring batch job?

We have multiple spring batch job.But Each of them needs to be started individually.

Is there any way to create a Master Job or any controller in spring which will be responsible for executing all other batch jobs? So that we just have to execute the master job only,and all other started automatically.

Upvotes: 2

Views: 1105

Answers (1)

Nenad Bozic
Nenad Bozic

Reputation: 3784

I just explained on this question how you can start spring application with all jobs loaded in separate context. We have restart job which is scheduled each 10min and it checks for latest failed execution and attempts to restart couple of more times.

Your use case is pretty much the same, you can define all jobs in separate contexts with own configuration files, in config you can tell spring batch not to run them on startup by setting spring.batch.job.enabled: false and you can write your own launcher which uses JobExplorer to start jobs for you and you can schedule it or something.

Something like:

@Component
@EnableScheduling
public class AllJobLauncher {

    @Autowired
    JobExplorer jobExplorer;

    @Autowired
    private JobLauncher jobLauncher;
    @Autowired
    private JobRegistry jobRegistry;

    @Scheduled(cron = "${some.cron:0 0/10 * * * ?}")
    public void launchAllJobs() throws JobExecutionException {
        final List<String> jobNames = jobExplorer.getJobNames();

        for (final String jobName : jobNames) {
             final Job job = jobRegistry.getJob(getJobName(organizationId));
             final JobParameters jobParameters = new JobParametersBuilder() //build parameters

             jobLauncher.run(job, jobParameters);
         }
    }

Just pay attention that JobLauncher in spring batch is by default sync so launcher will wait until job finishes. If you want to start jobs async you must place this configuration somewhere:

@Bean
public JobLauncher jobLauncher() {
    final SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
    jobLauncher.setJobRepository(jobRepository);
    final SimpleAsyncTaskExecutor simpleAsyncTaskExecutor = new SimpleAsyncTaskExecutor();
    jobLauncher.setTaskExecutor(simpleAsyncTaskExecutor);
    return jobLauncher;
 }

Upvotes: 4

Related Questions