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:

  1. If it's not done already, add the Spring Batch configuration class to the getServletConfigClasses()method in your class extending AbstractAnnotationConfigDispatcherServletInitializer:
    public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{AppConfig.class, BatchConfig.class};
    }
  2. Add the @EnableScheduling annotation to the Spring Batch configuration class:
    @Configuration ...

Get Spring Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.