How Spring Boot run batch jobs

Evgeni Dimitrov picture Evgeni Dimitrov · May 3, 2014 · Viewed 28.9k times · Source

I followed this sample for Spring Batch with Boot.

When you run the main method the job is executed. This way I can't figure out how one can control the job execution. For example how you schedule a job, or get access to the job execution, or set job parameters.

I tried to register my own JobLauncher

@Bean
public JobLauncher jobLauncher(JobRepository jobRepo){
    SimpleJobLauncher simpleJobLauncher = new SimpleJobLauncher();
    simpleJobLauncher.setJobRepository(jobRepo);
    return simpleJobLauncher;
}

but when I try to use it in the main method:

public static void main(String[] args) {
    ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args);    
    JobLauncher jobLauncher = ctx.getBean(JobLauncher.class);
    //try catch removed for readability
    jobLauncher.run(ctx.getBean(Job.class), new JobParameters());   
}

The job is again executed when the context is loaded and I got JobInstanceAlreadyCompleteException when I try to run it manually. Is there a way to prevent the automatic job execution?

Answer

Evgeni Dimitrov picture Evgeni Dimitrov · May 3, 2014

The jobs execution can be prevented by setting

spring.batch.job.enabled=false

in application.properties. Or you can use spring.batch.job.names it takes a comma-delimited list of job names that will be run.

Taken from here: how to stop spring batch scheduled jobs from running at first time when executing the code?