Schedule#
Sometimes, it is necessary to use the scheduling function to implement certain features. For example, scheduling the sending of emails or push notifications.
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 empty, which means that only 6 positions need to be set.
From left to right, the order is: seconds, minutes, hours, day of the month, month, day of the week, year.
Their values are as follows:
- 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.
It also supports 3,6,9
to represent a list of values, and 2/10
to represent starting from 2 and incrementing by 10 each time.
Delayed tasks#
There are two types of delays: delay after start and delay after completion.
fixedDelay#
fixedDelay means delaying the execution after the previous execution by a certain amount of time.
fixedRate#
fixedRate means starting the timer after the previous execution starts, and executing after a certain amount of time.