the command-line runners can be used as a place to start the scheduled executor thread pool in order to run the worker threads in intervals. While this works, Spring provides us with a more concise configuration to accomplish the same
Goal: @EnableScheduling
First add the @EnableScheduling annotation to the Application class
@SpringBootApplication
@EnableScheduling
public class BookPubApplication {
@Bean
public StartupRunner schedulerRunner() {
return new StartupRunner();
}
public static void main(String[] args) {
SpringApplication.run(BookPubApplication.class, args);
}
}
@Scheduled can only be used on no-argument methods
public class StartupRunner implements CommandLineRunner {
Log logger = LogFactory.getLog(getClass());
@Autowired
private BookRepository bookRepository;
@Override
public void run(String... args) throws Exception {
logger.info("Number of books: " + bookRepository.count());
}
@Scheduled(initialDelay = 1000, fixedRate = 3000)
public void run() {
logger.info("Number of books: " + bookRepository.count());
}
}
@EnableScheduling is not a Spring Boot annotation, but a Spring Context module annotation. it and
Both @SpringBootApplication and @EnableAutoConfiguration are meta-annotations. It utilizes @Import internally
Imports SchedulingConfiguration, which in turn creates ScheduledAnnotationBeanPostProcessor, and then
Scan those Spring Beans that have the @Scheduled annotation, and for each annotated method with no parameters, the corresponding executor
A thread pool will be created.