Scheduling executors
Earlier in this chapter, we discussed how the command-line runners can be used as a place to start the scheduled executor thread pools in order to run the worker threads in intervals. While that is certainly a possibility, Spring provides you with a more concise configuration to achieve the same goal: @EnableScheduling
.
Getting ready
We will enhance our application so that it will print a count of books in our repository every 10 seconds. To achieve this, we will make the necessary modifications to the BookPubApplication
and StartupRunner
classes.
How to do it…
- Let's add an
@EnableScheduling
annotation to theBookPubApplication
class, as follows:@SpringBootApplication @EnableScheduling public class BookPubApplication {…}
- As an
@Scheduled
annotation can be placed only on methods without arguments, let's add a newrun()
method to theStartupRunner
class and annotate it with the@Scheduled
annotation, as shown in the following line:@Scheduled(initialDelay = 1000, fixedRate = 10000) public void run() { logger.info("Number of books: " + bookRepository.count()); }
- Start the application by executing
./gradlew clean bootRun
from the command line so as to observe theNumber of books: 0
message that shows in the logs every 10 seconds.
How it works…
Like some other annotations that we discussed in this chapter and will further discuss in the book, @EnableScheduling
is not a Spring Boot annotation, but instead is a Spring Context module annotation. Similar to the @SpringBootApplication
and @EnableAutoConfiguration
annotations, this is a meta-annotation and internally imports the SchedulingConfiguration
via the @Import(SchedulingConfiguration.class)
instruction, which can be seen if looked found inside the code for the @EnableScheduling
annotation class.
ScheduledAnnotationBeanPostProcessor
that will be created by the imported configuration will scan the declared Spring Beans for the presence of the @Scheduled
annotations. For every annotated method without arguments, the appropriate executor thread pool will be created. It will manage the scheduled invocation of the annotated method.