Mastering Spring Boot Scheduled Tasks: From Basics to Distributed Locks
This tutorial explains how to create and configure scheduled tasks in Spring Boot, demonstrates code examples for simple 5‑second intervals, details the @Scheduled annotation parameters, and discusses the pitfalls of clustering without distributed locks.
We often need to send SMS, emails, or monitor flags periodically in Spring Boot applications.
Create Scheduled Task
In Spring Boot, creating a scheduled task is simple. Add @EnableScheduling to the main class to enable scheduling.
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}Create a component that contains the scheduled method.
@Component
public class ScheduledTasks {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
log.info("现在时间:" + dateFormat.format(new Date()));
}
}Running the application prints the current time every five seconds.
2021-07-13 14:57:01.411 INFO ... : 现在时间:14:57:01
2021-07-13 14:57:06.412 INFO ... : 现在时间:14:57:06
...@Scheduled Annotation Details
The @Scheduled annotation can be configured with several attributes extracted from its source:
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Schedules.class)
public @interface Scheduled {
String cron() default "";
String zone() default "";
long fixedDelay() default -1;
String fixedDelayString() default "";
long fixedRate() default -1;
String fixedRateString() default "";
long initialDelay() default -1;
String initialDelayString() default "";
}cron: use a cron expression to define execution rules.
zone: time zone for cron parsing.
fixedDelay: interval between the end of the last execution and the start of the next (ms).
fixedDelayString: same as fixedDelay but parsed with java.time.Duration.
fixedRate: interval between the start of successive executions (ms); if a previous execution is still running, it is queued.
fixedRateString: same as fixedRate with Duration parsing.
initialDelay: delay before the first execution.
initialDelayString: same as initialDelay with Duration parsing.
Considerations and Advanced Topics
While this approach works in a single‑process environment, it lacks coordination in a clustered deployment. Multiple instances would trigger the task simultaneously, leading to duplicate processing or data inconsistency.
To avoid this, use a distributed lock (e.g., Redis, Zookeeper) so that only one instance runs the task at a time.
Full Project Example
The complete source code is available in the chapter7-1 directory of the repository:
GitHub: https://github.com/dyc87112/SpringBoot-Learning/tree/master/2.x
Gitee: https://gitee.com/didispace/SpringBoot-Learning/tree/master/2.x
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
