I'm developing with Spring Batch using Spring Boot.
I'm with the minimal configuration provided by Spring Boot and defined some Jobs (no XML configuration at all). But when I run the application,
SpringApplication.run(App.class, args);
the jobs are sequentially executed in some arbitrary order.
I'm defining the jobs this way in @Configuration
annotated classes, Spring do the rest:
@Bean
public Job requestTickets() {
return jobBuilderFactory.get(Config.JOB_REQUEST_TICKETS)
.start(stepRequestTickets())
.build();
}
How can I instruct the framework to run the jobs in a certain order?
EDIT: Could this warning give a hint? (Maybe has nothing to be)
2016-12-29 17:45:33.320 WARN 3528 --- [main] o.s.b.c.c.a.DefaultBatchConfigurer: No datasource was provided...using a Map based JobRepository
1.You first disable automatic job start by specifying spring.batch.job.enabled=false
in application.properties
2.In your main class, do - ApplicationContext ctx = SpringApplication.run(SpringBatchMain.class, args);
assuming your main class is named - SpringBatchMain.java.
This will initialize context without starting any jobs.
3.Once context is initialized, either you can do - JobLauncher jobLauncher = (JobLauncher) ctx.getBean("jobLauncher");
or do Autowired
for this JobLauncher bean in main class and launch specific jobs sequentially in specific sequential order by invoking , jobLauncher.run(job, jobParameters)
.
You can get specific job
instances from context initialized at step # 2.
You can always use any ordered collection to put your jobs there and launch jobs by iterating over that collection.
4.This above technique works as long as your JobLauncher is configured to be synchronous i.e. main thread waits for jobLauncher.run()
call to complete and that is default behavior of jobLauncher.
If you have defined your jobLauncher to use AsyncTaskExecutor then jobs will be started in parallel and sequential ordering will not be maintained.
Hope it helps !!
EDIT:
I was experimenting with @Order
annotation as pointed by Stephane Nicoll and it seems to help only in creating an Ordered collection of jobs and that you can iterate and launch jobs in that order.
This below component gives me jobs in Order specified ,
@Component
public class MyJobs {
@Autowired
private List<Job> jobs;
public List<Job> getJobs() {
return jobs;
}
}
and I can do , MyJobs myJobs = (MyJobs) ctx.getBean("myJobs");
in main class provided bean is defined,
@Bean
public MyJobs myJobs() {
return new MyJobs();
}
I can iterate over myJobs
and launch jobs in that order as specified by @Order annotation.
Order them.
@Bean
@Order(42)
public Job requestTickets() {
return jobBuilderFactory.get(Config.JOB_REQUEST_TICKETS)
.start(stepRequestTickets())
.build();
}
See the javadoc of @Order
for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With