Schedule#
Sometimes it is necessary to use timing functions to implement certain features. For example, sending emails or notifications at a specific time.
In this case, the Scheduled annotation is needed.
Enabling Schedule in SpringBoot#
-
First, add the
@EnableScheduling
annotation to the startup class. -
Create a component.
-
Write the schedule method and add the
@Scheduled
annotation.
For example:
@Component
public class TestSchedule {
Logger logger = LoggerFactory.getLogger(TestSchedule.class);
@Scheduled(cron = "0 * * * * *")
public void testCommon(){
logger.info("common "+Instant.now().toString());
}
@Scheduled(fixedDelay = 1000)
public void testFixDelay(){
logger.info("delay "+Instant.now().toString());
}
@Scheduled(initialDelay = 1000,fixedDelay = 1000)
public void testInitDelay(){
logger.info("delay "+Instant.now().toString());
}
@Scheduled(fixedRate = 2000)
public void testRateDelay(){
logger.info("rate "+Instant.now().toString());
}
}
Configuration of Annotations#
First type, scheduled tasks#
The first type is scheduled tasks, where the cron
value in @Scheduled
is added with an expression to indicate when the method should be executed.
cron-like expression#
The expression is generally in the format: * * * * * * *
.
There are a total of 7 positions, and the last one can be left blank, which means it can be set with only 6 positions.
From left to right, the order is: seconds, minutes, hours, day of the month, month, day of the week, year.
Their values are respectively:
- 0-59 seconds
- 0-59 minutes
- 0-23 hours
- 1-31 day of the month
- 1-12 month
- 1-7 day of the week
- 1970-2099 year
Examples#
0 * * * * ?
means triggering every time the seconds reach 0, i.e., every minute.
0 0 * * * ?
means triggering every time the minutes reach 0, i.e., every hour. It can also be written as * 0 * * * *
.
* * 3 * * ?
means executing at 3 o'clock every day.
* * 3 15 * ?
means executing at 3 o'clock on the 15th day of each month. The question mark represents uncertainty or flexibility because day of the week and day of the month conflict with each other.
* * 3 ? * 1
means executing at 3 o'clock every Monday. The corresponding day is represented by a question mark.
* * 3-5 * * ?
means executing at 3, 4, and 5 o'clock every day. The - represents a range.
There is also the option to use 3,6,9
to represent a list of values, and 2/10
to represent starting from 2 and incrementing by 10.
Delayed tasks#
There are two types of delays: delay after start and delay after completion.
fixedDelay#
fixedDelay represents the delay after the previous execution before the next execution.
fixedRate#
fixedRate represents starting the timer after the previous execution and executing after a certain time.