rayman
rayman

Reputation: 21596

Best approach to chain two jobs one after another using Spring Batch

I am having two jobs(Job1,Job2) Job2 is depended on the results of job1 so it has to wait till job 1 finished

I need to chain them somehow:

  1. When job1 finish it needs to call job2. how to do that? using tasklet in the end which will call job2?

  2. The other way could be that the invoker(which is some scheduler service) will be responsible for calling job2 as soon as job1 returns - not really good because than ill need to call job1 synchronously.

How would you implement two chained (and depended jobs) using spring batch?

Thank you.

Upvotes: 7

Views: 20351

Answers (2)

Jimmy Praet
Jimmy Praet

Reputation: 2370

You can use a JobStep to launch the second job from within the first job. See 5.3.6 Externalizing Flow Definitions and Dependencies Between Jobs

Upvotes: 7

user7375303
user7375303

Reputation:

This is my way of launching two (a list) jobs one after the other:

1- Declare the two job beans with @Order

@Order(1) // The first in the List
@Bean(name = "firstJob")
public Job firstJob() { .... }

@Order(2) // Second job to be launched
@Bean(name = "secondJob")
public Job secondJob() { .... }

2- Inject the list of jobs

@Autowired
List<Job> jobs;

3- Launch them

    public void run(String... args) {
    JobParameters params = new JobParametersBuilder()
            .addString("JobID", String.valueOf(System.currentTimeMillis()))
            .toJobParameters();
    jobs.forEach(job -> {
        try {
            jobLauncher.run(job, params);
        } catch (Exception e) {
            logger.error("Job {} cannot be executed", job.getName());
            e.printStackTrace();
        }
    });
}

I hope this helps new people reading this post

Upvotes: 0

Related Questions