How @ Scheduled of Spring dynamically updates cron expressions

  • 2021-10-24 22:52:03
  • OfStack

Common local timing is written as follows:


 @Scheduled(cron = "0/5 * * * * ?")
    private void test() {
        log.info(" Business processing logic. . . 5 Seconds 1 Times ");
    }

If you want to update the cron expression dynamically, you can write this:

First, write a class so that cron expressions always read the values of member variables.

Write another controller, and you can dynamically set the cron expression by calling the set method


@Lazy(false)
@Component
@EnableScheduling
public class SpringDynamicCornTask implements SchedulingConfigurer {
    private static final Logger logger = LoggerFactory.getLogger(SpringDynamicCornTask.class);
    private static final String DEFAULT_CRON = "0/5 * * * * ?";
    private String cron = DEFAULT_CRON;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(() -> {
            logger.info(" True task execution logic. . . ");
        }, triggerContext -> {
            CronTrigger trigger = new CronTrigger(cron);
            return trigger.nextExecutionTime(triggerContext);
        });
    }
    public void setCron(String cron) {
        System.out.println(" Original cron : "+this.cron+" Updated cron : "+cron);
        this.cron = cron;
    }
    public String getCron() {
        return this.cron;
    }
}

@RestController
public class TestController {
    @Autowired
    private SpringDynamicCornTask springDynamicCornTask;

    @RequestMapping("/setCron")
    public String setCron(){
        springDynamicCornTask.setCron("0/10 * * * * ?");
        return "success";
    }
    @RequestMapping("/getCron")
    public String getCron(){
        String cron = springDynamicCornTask.getCron();
        return "cron:"+cron;
    }
}

By calling this/setCron directly, you can change cron from once every 5 seconds to once every 10 seconds.

Of course, it is not difficult to move cron to the database for centralized management on this basis.

Scheduled cron Expression of Spring Timing Task

An cron expression has at least 6 (and possibly 7) space-separated time elements.

In order

Seconds (0 ~ 59)

Minutes (0 ~ 59)

Hours (0 ~ 23)

Days (months) (0 ~ 31, but you need to consider the number of days in your month)

Month (0 ~ 11)

Days (weeks) (1 ~ 7 1=SUN or SUN, MON, TUE, WED, THU, FRI, SAT)

7. Year (1970-2099)

Each element can be a value (e.g. 6), a continuous interval (9-12), an interval (8-18/4) (/for every 4 hours), a list (1, 3, 5), a wildcard. Since the "Date in Month" and "Date in Week" elements are mutually exclusive, you must set one of them? .

0 0 10, 14, 16 * *? Every day at 10 am, 2 pm and 4 pm
0 0/30 9-17 * *? Every half hour during working hours from 9 to 5
0 0 12? * WED means 12 noon every Wednesday
"0 0 12 * *? "Triggered at 12 noon every day
"0 15 10? * * "Triggered every day at 10:15 am
"0 15 10 * *? "Triggered every day at 10:15 am
"0 15 10 * *? * "Triggered every day at 10:15 am
"0 15 10 * *? 2005 "Triggered at 10:15 am every day in 2005
"0 * 14 * *? "Triggered every 1 minute between 2 pm and 2:59 pm every day
"0 0/5 14 * *? "Triggered every 5 minutes between 2 pm and 2:55 pm every day
"0 0/5 14, 18 * *? "Triggered every 5 minutes between 2 pm and 2:55 pm every day and between 6 pm and 6:55 pm
"0 0-5 14 * *? "Triggered every 1 minute between 2 pm and 2:05 pm every day
"0 10, 44 14? 3 WED "Triggered at 2:10 pm and 2:44 pm on Wednesday in March every year
"0 15 10? * MON-FRI "Triggered from Monday to Friday at 10:15 a.m.
"0 15 10 15 *? "Triggered at 10:15 am on the 15th of each month
"0 15 10 L *? "Triggered at 10:15 am on the last day of each month
"0 15 10? * 6L "Triggered at 10:15 am on Friday of the last week of each month
"0 15 10? * 6L 2002-2005 "Triggered at 10:15 a.m. on Friday, the last week of each month, 2002-2005
"0 15 10? * 6 # 3 "Triggered at 10:15 am on the 5th of the 3rd week of each month

Some subexpressions can contain 1 range or list

For example, the subexpression (day (week)) can be "MON-FRI", "MON, WED, FRI", "MON-WED, SAT"

The "*" character represents all possible values

Therefore, "*" means each month in a subexpression (month), and "*" means every day of the week in a subexpression (day (week))

The "/" character is used to specify the increment of a numeric value

For example, "0/15" in a subexpression (minutes) means every 15 minutes starting from the 0th minute

"3/20" in a subexpression (minutes) means every 20 minutes from the 3rd minute (it has the same meaning as "3, 23, 43")

"?" Character is only used in two subexpressions: day (month) and day (week), indicating that no value is specified

When one of the two subexpressions is specified with a value, in order to avoid conflicts, the value of the other subexpression needs to be set to "?"

The "L" character is used only for day (month) and day (week) subexpressions, which is an abbreviation of the word "last."

But its meaning in the two subexpressions is different.

In the day (month) subexpression, "L" represents the last day of a month

In the day (week) self expression, "L" means the last day of a week, that is, SAT

If there is specific content before "L", it has other meanings

For example, "6L" means the last 6 days of the month, and "FRIL" means the last week of the month

Note: When using the "L" parameter, do not specify a list or range because this can cause problems

Special characters allowed by the allowed value of the field

0-59 , - * /
0-59 , - * /
小时 0-23 , - * /
日期 1-31 , - * ? / L W C
月份 1-12 或者 JAN-DEC , - * /
星期 1-7 或者 SUN-SAT , - * ? / L C #
年(可选) 留空, 1970-2099 , - * /

Related articles: