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 * * * * |

Comments
Nothing yet. Say the first thing.
Sign in to join the conversation.