Spring @EnableScheduling Annotation Examples
- Details
- Written by Nam Ha Minh
- Last Updated on 23 July 2024   |   Print Email
In this post, I’d like to explain usage of the @EnableScheduling annotation in the Spring framework with some code examples.
This annotation is used to implement scheduled tasks in Spring applications, along with the @Scheduled annotation. It's a marker interface and has no attributes. You can mark a configuration, component, service or main class with @EnableScheduling annotation to enable task scheduling capability supported by Spring framework. The following code shows a simple example:
package net.codejava; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component @EnableScheduling public class MyTask { @Scheduled(initialDelay = 10000) public void work() { // task execution logic } }
This is example of a one-time task in Spring. The code in the work() method will be scheduled to be executed only once, after the initial delay of 10 seconds.
Behind the scene, the @EnableScheduling annotation imports the SchedulingConfiguration class that registers a ScheduledAnnotationBeanPostProcessor bean capable of detecting and processing Spring’s @Scheduled annotation.
Below is another example that shows the @EnableScheduling annotation is used in a configuration class:
package net.codejava; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; @Configuration @EnableScheduling public class AppConfig { @Bean public EmailTask task() { return new EmailTask(); } }
The EmailTask class is defined as follows:
package net.codejava; import org.springframework.scheduling.annotation.Scheduled; public class EmailTask { @Scheduled(cron = "0 15 10 * * ?") public void sendEmails() { // send email task } }
This task is scheduled to fire at 10:15 AM every day using cron-like expression. You can use the @EnableScheduling annotation at class level, in any container-managed type (component, service, configuration, etc).
Refer to this guide to learn more about scheduled tasks in Spring. You can also watch the video to see the coding in action:
Reference:
Other Spring Annotations:
- Spring @Service Annotation Examples
- Spring @Component Annotation Examples
- Spring @Repository Annotation Examples
- Spring @Configuration Annotation Examples
- Spring @Controller Annotation Examples
- Spring @RestController Annotation Examples
- Spring @Bean Annotation Examples
Comments