Book Image


Book Image


Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
About the Author
About the Reviewers

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 {
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{AppConfig.class, BatchConfig.class};
  2. Add the @EnableScheduling annotation to the Spring Batch configuration class:

    public class BatchConfig {
  3. Add an autowired JobLauncher field:

    JobLauncher jobLauncher;
  4. Add a method annotated with @Scheduled with a fixedDelay attribute in ms: