Reputation: 579
I'm using spring boot and I write a job that has only one step, and this step call a Tasklet.
This is the code:
@Configuration
public class ApiCallerJobConfiguration {
private Step createApiCallerTasklet(StepBuilderFactory steps) {
ApiCallerLogger.info("Create apiCallerTasklet");
return steps.get("createApiCallerTasklet")
.tasklet(new ApiCallerTasklet())
.build();
}
@Bean(name = "apiCallerJob")
public Job apiCallerJob(JobBuilderFactory jobs, StepBuilderFactory steps) {
ApiCallerLogger.info("Start apiCallerJob");
return jobs.get("apiCallerJob")
.start(createApiCallerTasklet(steps))
.build();
}
}
Using the debugger I noticed that I enter in this class twice: the first time ( I suppose ) during the startup phase of spring, and the second time when the "apiCallerJob" is launched effectively. The problem is that the first time the ApiCallerTasklet is created, the Tasklet method execute() is also called and it returns a non-blocking exception ( that because one of the job params is not yet enhanced ); after that, the execution continues and the second time that the tasklet is executed everything works correctly.
Although this error is non-blocking, I'd like to understand which is the problem.
The "apiCallerJob" is runned by this service:
@Service
public class JobServiceImpl implements JobService {
@Autowired
private JobLauncher jobLauncher;
@Autowired
@Qualifier("apiCallerJob")
private Job apiCallerJob;
@Override
public JobExecution runJob(String rootContext, String dateFrom, String dateTo) throws Exception{
JobParametersBuilder jobParametersBuilder = new JobParametersBuilder();
jobParametersBuilder.addDate(ApiCallerJobParams.EXEC_TIMESTAMP.toString(), new Date());
jobParametersBuilder.addString(ApiCallerJobParams.CONTEXT_ROOT.toString(), rootContext);
jobParametersBuilder.addString(ApiCallerJobParams.DATE_FROM.toString(), dateFrom);
jobParametersBuilder.addString(ApiCallerJobParams.DATE_TO.toString(), dateTo);
return jobLauncher.run(apiCallerJob, jobParametersBuilder.toJobParameters());
}
}
Upvotes: 2
Views: 1484
Reputation: 31600
By default, Spring Boot executes any job in your application context at startup. So I guess that's why you see your tasklet being executed twice: once at application startup and once when you invoke the API.
If you want to disable running jobs at startup you need to set the the property spring.batch.job.enabled=false
.
Upvotes: 2