Scheduling a job
Some jobs need to be executed regularly-every night, every hour, and so on. Spring makes this easy with the @Scheduled
annotation.
Getting ready
We will use the job defined in the Creating a job recipe.
How to do it…
Follow these steps to schedule the job:
If it's not done already, add the Spring Batch configuration class to the
getServletConfigClasses()
method in your class extendingAbstractAnnotationConfigDispatcherServletInitializer
:public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[]{AppConfig.class, BatchConfig.class}; }
Add the
@EnableScheduling
annotation to the Spring Batch configuration class:@Configuration @EnableBatchProcessing @EnableScheduling public class BatchConfig { ...
Add an autowired
JobLauncher
field:@Autowired JobLauncher jobLauncher;
Add a method annotated with
@Scheduled
with afixedDelay
attribute in ms:@Scheduled(fixedDelay...