4

I want to run two jobs one after the other. Yes, I did search online but they have solutions which involve adding the second job as a step in the first. But I have different requirement. I would get a notification after the first batch jobs execution is complete and the second one will run only after this notification is received. Is it even possible to run two jobs one after other in Spring boot. Please help!

  • Does [my this answer](http://stackoverflow.com/questions/41364220/how-to-run-spring-batch-jobs-in-certain-order-spring-boot/41437552#41437552) help? – Sabir Khan Feb 17 '17 at 06:22

1 Answers1

3

May be Easiest Solution is to add a JobExecutionListener for callback after FirstJob completes. And in AfterJob callback start the second Job. Since you get the executionContext of the FirstJob you can apply job run strategy based on Job.

public class KpJobListener implements JobExecutionListener {

    private final static Logger LOG = LoggerFactory.getLogger(KpJobListener.class);

    private Job job;
    private JobLauncher jobLauncher;

    public KpJobListener(final Job job, final JobLauncher jobLauncher) {
        this.job = job;
        this.jobLauncher = jobLauncher;
    }

    @Override
    public void beforeJob(JobExecution jobExecution) {
        LOG.info("Starting job {}");
    }

    @Override
    public void afterJob(JobExecution jobExecution) {
        LOG.info("Job is completed job");
        CompletableFuture.runAsync(()->{
            try {
                jobLauncher.run(job, new JobParametersBuilder().toJobParameters());
            } catch (JobExecutionAlreadyRunningException | JobRestartException | JobInstanceAlreadyCompleteException
                    | JobParametersInvalidException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        });
    }

}

Sample Spring-batch.xml

<batch:job id="kpJob1" incrementer="jobIncrementer"
        restartable="true">
        <batch:listeners>
            <batch:listener>
                <bean class="com.kp.job.KpJobListener">
                    <constructor-arg name="job" ref="kpJob2" />
                    <constructor-arg name="jobLauncher" ref="jobLauncher" />
                </bean>
            </batch:listener>
        </batch:listeners>
        <batch:step id="kpJob1.step1" allow-start-if-complete="true">
            <batch:tasklet>
                <bean class="com.kp.job.step.task.KpTasklet" />
            </batch:tasklet>
        </batch:step>
    </batch:job>

You can enhance this approach for messaging service, which could be neat design.

Draken
  • 3,134
  • 13
  • 34
  • 54
Karthik Prasad
  • 9,662
  • 10
  • 64
  • 112