1 | initial version |
To schedule a Spring Batch job to run automatically when the application starts up, you can use the @Scheduled
annotation on a method in a @Configuration
class.
First, annotate the configuration class with @EnableScheduling
so that Spring knows to look for scheduled tasks.
Then, create a method in the configuration class and annotate it with @Scheduled
to indicate that it should be run according to a fixed schedule.
Inside the method, use the JobLauncher
to launch the Spring Batch job.
Here is an example:
@Configuration
@EnableScheduling
public class BatchConfig {
@Autowired
private JobLauncher jobLauncher;
@Autowired
private Job myJob;
@Scheduled(fixedDelay = 1000) // run every second
public void runJob() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {
jobLauncher.run(myJob, new JobParameters());
}
}
In this example, the runJob()
method will be automatically executed every second due to @Scheduled(fixedDelay = 1000)
. Inside the method, the JobLauncher
launches the myJob
Spring Batch job with an empty JobParameters
object.
Note: If you don't want your job to be executed repeatedly, you can change fixedDelay
to something like fixedRate
or use a Cron expression to schedule your job according to your needs.