Enable the resource
There are many ways to manage repeating tasks in Spring, but by far the easiest one is using the built-in Scheduler.
To enable it you just have to annotate the main class with @EnableScheduling
.
Itβs worth pointing out that the default behavior doesnβt allow for parallel execution of tasks.
To do this youβll also use @EnableAsync
on the main class and @Async
on the desired function.
Types of Scheduling
Spring offers three ways of managing recurrent jobs:
Fixed Rate
Runs the method every βXβ milliseconds.
Enable it with @Scheduled(fixedRate = timeInMilliseconds)
.
@Scheduled(fixedRate = 2000)public void repeatEveryTwoSeconds() { System.out.println("I run every two seconds, no matter the previous run!");}
Fixed Delay
Runs the method βXβ milliseconds after the previous execution is done.
Enable it with @Scheduled(fixedDelay = timeInMilliseconds)
.
@Scheduled(fixedRate = 2000)public void repeatAfterTwoSeconds() { System.out.println("I run two seconds after the previous run is over!");}
You can also adjust the initial execution delay adding initialDelay
, as such: @Scheduled(fixedDelay = 2000, initialDelay = 3000)
.
Cron
For greater flexibility, Spring allows us to adjust the repetition pattern with Cron.
Enable it with @Scheduled(cron = "* * * * * *")
.
@Scheduled(cron = "0 0 0 * * *")public void repeatEveryMidnight() { System.out.println("I run every day at midnight");}
Unix cron vs Spring cron
There are some subtle differences between the cron schedules youβll set up in Spring applications and the ones youβll find in your typical Linux machine.
Unix Cron
ββββββββββββββ minute (0 - 59)β ββββββββββββββ hour (0 - 23)β β ββββββββββββββ day of month(1 - 31)β β β ββββββββββββββ month (1 - 12)β β β β ββββββββββββββ day of week (0 - 6) (Sunday to Saturday)β β β β ββ β β β β* * * * *
Spring Cron
ββββββββββββββ second (0-59) β ββββββββββββββ minute (0 - 59) β β ββββββββββββββ hour (0 - 23) β β β ββββββββββββββ day of month (1 - 31) β β β β ββββββββββββββ month (1 - 12) β β β β β ββββββββββββββ day of week (0 - 7) (Saturday to Saturday) β β β β β β β β β β β β * * * * * *
As you can see, where Unix-like Cron has only 5 fields (some systems have 6, but thatβs used for user permissions), Spring-like Cron has 6; adding the ability do manage tasks my the second.
Moreover, while traditional Cron only supports macros in some systems, Springs version does so by default:
Macro | Description | Cron |
---|---|---|
@yearly | Once a year | 0 0 0 1 1 * |
@monthly | Once a month | 0 0 0 1 * * |
@weekly | Once a week | 0 0 0 * * 0 |
@daily | Once a day | 0 0 0 * * * |
@hourly | Once evey hour | 0 0 * * * * |