1. Trigger conditions for scheduled tasks

Add @enablesCheduling to the Application startup class

2. Add an annotation to the class with the timed method: @Component, which adds the timed task class to Spring Bean management.

@scheduled (cron = “Scheduled 1 *?”) ), the cron expression executes the method once a minute.

The Scheduled changes have been applied

1, fixedDelay

@scheduled (fixedDelay = 5000) public void testFixedDelay(){try {log.info(" current time: "+ dateutil.now ()); Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); }}Copy the code

Each task is delayed by 3 seconds, then the current time is printed.

Summary of fixedDelay rules:

After the first task is complete, wait another 5 seconds and then execute the second task.

2, fixedRate

@scheduled (fixedRate = 5000) public void testFixedRate(){try {log.info(" current time: "+ dateutil.now ()); Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); }}Copy the code

After a task is started, it is executed every 5 seconds.

If the delay time is changed to 8 seconds, the output becomes 8 seconds, as shown below:

Summary of fixedRate rules:

If the scheduled task is set to be executed every five seconds, if the previous task takes more than five seconds, the second task will be executed immediately after the completion of the previous task. If the first task takes less than 5 seconds, execute the second task after 5 seconds.

3. How can I help you?

Corn expressions can be expressed in seconds, minutes, hours, days, weeks, months, and years:

Seconds minute hour day week month year 0 * 14 * *? * : indicates that the command is executed every minute from 14:00 every day. 0, 0, 14 * *? * : perform a task at 14:00 every day.Copy the code

The rationality of Cron can be tested by using Corn to generate an expression:.

Corn Example: Run this command every 2 minutes.

@Scheduled(cron = "0 0/2 * * * ?" ) public void test() { int j = 0; for (int i = 0; i < 10; I++) {log.info("Scheduled tests "); j++; Log.info ("j value :" + j); try { Thread.sleep(1000 * 20); } catch (InterruptedException e) { e.printStackTrace(); }}}Copy the code

Effect:

Conclusion:

As shown in the code above, set the test() method to execute every 2 minutes. However, if the execution time of the previous task exceeds 2 minutes, the second task will wait for a period of time after the completion of the previous task before executing the second task.