Usage
You typically create cron triggers with the @Scheduled
annotation, which uses CronExpression
internally, as of Spring Framework 5.3. This means that you can already start using the New Features if you are on that version.
If you want to play around with CronExpression
yourself, you can create one through the static parse method:
1 2 3 |
var expression = CronExpression.parse("10 * * * * *"); var result = expression.next(LocalDateTime.now()); System.out.println(result); |
1 2 3 4 5 6 7 8 9 |
┌───────────── second (0-59) │ ┌───────────── minute (0 - 59) │ │ ┌───────────── hour (0 - 23) │ │ │ ┌───────────── day of the month (1 - 31) │ │ │ │ ┌───────────── month (1 - 12) (or JAN-DEC) │ │ │ │ │ ┌───────────── day of the week (0 - 7) │ │ │ │ │ │ (or MON-SUN -- 0 or 7 is Sunday) │ │ │ │ │ │ * * * * * * |
Every 5 Seconds Example
1 |
Use @Scheduled(fixedRate = 5000). You can also use a CRON expression @Scheduled(cron = "*/5 * * * * ?") but it seems like an overkill. |
Some rules apply:
- A field may be an asterisk (
*
), which always stands for “first-last”. For the day-of-the-month or day-of-the-week fields, a question mark (?
) may be used instead of an asterisk. - Commas (
,
) are used to separate items of a list. - Two numbers separated with a hyphen (
-
) express a range of numbers. The specified range is inclusive. - Following a range (or
*
) with/
specifies the interval of the number’s value through the range. - English names can also be used for the day-of-month and day-of-week fields. Use the first three letters of the particular day or month (case does not matter).
Here are some examples:
Cron Expression | Meaning |
---|---|
|
top of every hour of every day |
|
every ten seconds |
|
8, 9 and 10 o’clock of every day |
|
6:00 AM and 7:00 PM every day |
|
8:00, 8:30, 9:00, 9:30, 10:00 and 10:30 every day |
|
on the hour nine-to-five weekdays |
|
every Christmas Day at midnight |
The next
method returns the next occurrence of the trigger or null
if there is none. It takes a java.time.temporal.Temporal
as a parameter, which means it accepts not only LocalDateTime
but also ZonedDateTime
if time-zones are relevant.
New Features
Using the java.time
APIs let us introduce several new features that put Spring’s support for cron expressions on an equal footing with other schedulers. You can start using these features in @Scheduled
as of Spring Framework 5.3.
Macros
Expressions such as 0 0 * * * *
are hard for humans to parse and are, therefore, hard to fix in case of bugs. To improve readability, Spring now supports the following macros, which represent commonly used sequences. You can use these macros instead of the six-digit value, thus: @Scheduled(cron = "@hourly")
.
Macro | Meaning |
---|---|
|
once a year ( |
|
once a month ( |
|
once a week ( |
|
once a day ( |
|
once an hour, ( |
–
Ref : https://spring.io/blog/2020/11/10/new-in-spring-5-3-improved-cron-expressions
Ref : https://www.baeldung.com/spring-batch-start-stop-job
–