0
0
SpringbootHow-ToBeginner · 3 min read

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-59
  • minute: 0-59
  • hour: 0-23
  • day of month: 1-31
  • month: 1-12 or JAN-DEC
  • day 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 @EnableScheduling in 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 week and day of month fields 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 zone attribute.
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

FieldAllowed ValuesDescription
Seconds0-59Seconds within a minute
Minutes0-59Minutes within an hour
Hours0-23Hours within a day
Day of Month1-31Day of the month
Month1-12 or JAN-DECMonth of the year
Day of Week0-7 or SUN-SATDay 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.