Spring Scheduled Tasks Cron Guide

The time configuration for Spring scheduled tasks is specified using a Cron expression.

A Cron expression is a string that consists of 6 or 7 spaced fields representing seconds, minutes, hours, day of month, month, day of week, and year (optional). The specific syntax rules are as follows:

  1. Seconds (0-59)
  2. Minutes (0-59)
  3. Hour (0-23)
  4. Date (1-31)
  5. Months (1-12 or JAN-DEC)
  6. Use the numbers 1-7 to represent the days of the week, with 1 being Sunday and 7 being Saturday.
  7. Year (optional)

Here are some common examples of Cron expressions:

  1. “0 * * * * *”: run every minute
  2. “0 0 * * * *”: Run every hour on the hour.
  3. “0 0 12 * * *”:Run once every day at noon.
  4. At every hour from 8 AM to 6 PM every day.
  5. “Every Monday to Friday at 12:00 PM”
  6. “0 0 12 ? * 6L” : It will be executed at 12 PM on the last Friday of every month.

You can specify the Cron expression for a scheduled task by using the @Scheduled annotation in the Spring configuration file, as shown below:

@Component
public class MyScheduledTask {

    @Scheduled(cron = "0 * * * * *")
    public void run() {
        // 定时任务的逻辑
    }

}

After this configuration, the scheduled task will be executed according to the specified Cron expression.

bannerAds