I am trying to run my batch job from a controller. It will be either fired up by a cron job or by accessing a specific link. I am using Spring Boot, no XML just annotations.
In my current setting I have a service that contains the following beans:
@EnableBatchProcessing
@PersistenceContext
public class batchService {
@Bean
public ItemReader<Somemodel> reader() {
...
}
@Bean
public ItemProcessor<Somemodel, Somemodel> processor() {
return new SomemodelProcessor();
}
@Bean
public ItemWriter writer() {
return new CustomItemWriter();
}
@Bean
public Job importUserJob(JobBuilderFactory jobs, Step step1) {
return jobs.get("importUserJob")
.incrementer(new RunIdIncrementer())
.flow(step1)
.end()
.build();
}
@Bean
public Step step1(StepBuilderFactory stepBuilderFactory,
ItemReader<somemodel> reader,
ItemWriter<somemodel> writer,
ItemProcessor<somemodel, somemodel> processor) {
return stepBuilderFactory.get("step1")
.<somemodel, somemodel> chunk(100)
.reader(reader)
.processor(processor)
.writer(writer)
.build();
}
}
As soon as I put the @Configuration
annotation on top of my batchService class, job will start as soon as I run the application. It finished successfully, everything is fine. Now I am trying to remove @Configuration annotation and run it whenever I want. Is there a way to fire it from the controller?
Thanks!
If you want to launch your jobs periodically, you can combine Spring Scheduler and Spring Batch. Here is a concrete example : Spring Scheduler + Batch Example. If you want to re-launch your job continually (Are you sure !), You can configure a Job Listener on your job. Then, through the method jobListener.
Get the id values of all the running JobExecutions with the given job name. Summarise the StepExecution instances belonging to the JobExecution with the supplied id, giving details of status, start and end times etc. Summarise the JobExecution with the supplied id, giving details of status, start and end times etc.
You need to create a application.yml file in the src/main/resources and add following configuration:
spring.batch.job.enabled: false
With this change, the batch job will not automatically execute with the start of Spring Boot. And batch job will be triggered when specific link.
Check out my sample code here: https://github.com/pauldeng/aws-elastic-beanstalk-worker-spring-boot-spring-batch-template
You can launch a batch job programmatically using JobLauncher
which can be injected into your controller. See the Spring Batch documentation for more details, including this example controller:
@Controller
public class JobLauncherController {
@Autowired
JobLauncher jobLauncher;
@Autowired
Job job;
@RequestMapping("/jobLauncher.html")
public void handle() throws Exception{
jobLauncher.run(job, new JobParameters());
}
}
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