How to Use Cron Expression in Spring Boot for Scheduled Tasks
In Spring Boot, use the
@Scheduled annotation with the cron attribute to run tasks on a schedule defined by a cron expression. Enable scheduling by adding @EnableScheduling to a configuration class. The cron expression defines when the method runs, like every minute or at specific times.Syntax
The cron expression in Spring Boot uses six fields separated by spaces: second, minute, hour, day of month, month, day of week. Each field can have specific values or special characters to define the schedule.
second: 0-59minute: 0-59hour: 0-23day of month: 1-31month: 1-12 or JAN-DECday of week: 0-7 or SUN-SAT (0 and 7 both mean Sunday)
Example: "0 0 12 * * ?" means every day at 12:00 PM.
java
@Scheduled(cron = "0 0 12 * * ?") public void runAtNoon() { // task code here }
Example
This example shows a Spring Boot component that prints a message every 10 seconds using a cron expression.
java
import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.time.LocalTime; @Component @EnableScheduling public class ScheduledTask { @Scheduled(cron = "*/10 * * * * *") public void printEveryTenSeconds() { System.out.println("Task executed at: " + LocalTime.now()); } }
Output
Task executed at: 10:00:10.123
Task executed at: 10:00:20.124
Task executed at: 10:00:30.125
... (every 10 seconds)
Common Pitfalls
- Forgetting to add
@EnableSchedulingin a configuration class disables scheduling. - Using a 5-field cron expression instead of 6 fields causes errors; Spring requires 6 fields.
- Misunderstanding the
day of weekandday of monthfields can cause unexpected schedules; use?in one of these fields if you don't want to specify it. - Time zone differences can affect when the task runs; specify time zone if needed with
zoneattribute.
java
/* Wrong: 5 fields, missing seconds */ @Scheduled(cron = "0 0 12 * *") public void wrongSchedule() {} /* Right: 6 fields with seconds */ @Scheduled(cron = "0 0 12 * * ?") public void correctSchedule() {}
Quick Reference
| Field | Allowed Values | Description |
|---|---|---|
| Seconds | 0-59 | Seconds within a minute |
| Minutes | 0-59 | Minutes within an hour |
| Hours | 0-23 | Hours within a day |
| Day of Month | 1-31 | Day of the month |
| Month | 1-12 or JAN-DEC | Month of the year |
| Day of Week | 0-7 or SUN-SAT | Day of the week (0 and 7 = Sunday) |
Key Takeaways
Use @Scheduled with a 6-field cron expression to schedule tasks in Spring Boot.
Always add @EnableScheduling to enable scheduled tasks.
Use '?' in either day-of-month or day-of-week to avoid conflicts.
Specify time zone if your schedule depends on a particular zone.
Test cron expressions carefully to ensure correct timing.