Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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
    @EnableBatchProcessing
    @EnableScheduling
    public class BatchConfig {
    ...
  3. Add an autowired JobLauncher field:

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

    @Scheduled(fixedDelay...