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)
.
Fixed Delay
Runs the method βXβ milliseconds after the previous execution is done.
Enable it with @Scheduled(fixedDelay = timeInMilliseconds)
.
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 = "* * * * * *")
.
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
Spring Cron
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 * * * * |