Using the @Scheduled Annotation
The Scheduled annotation can be added to any method of a bean, and you should set one of the fixedRate
, fixedDelay
, or cron
members.
Remember that the scope of a bean impacts behaviour. A @Singleton bean shares state (the fields of the instance) each time the scheduled method is executed, while for a @Prototype bean a new instance is created for each execution. |
Scheduling at a Fixed Rate
To schedule a task at a fixed rate, use the fixedRate
member. For example:
Fixed Rate Example
@Scheduled(fixedRate = "5m")
void everyFiveMinutes() {
System.out.println("Executing everyFiveMinutes()");
}
Fixed Rate Example
@Scheduled(fixedRate = "5m")
void everyFiveMinutes() {
println "Executing everyFiveMinutes()"
}
Fixed Rate Example
@Scheduled(fixedRate = "5m")
internal fun everyFiveMinutes() {
println("Executing everyFiveMinutes()")
}
The task above executes every five minutes.
Scheduling with a Fixed Delay
To schedule a task so it runs five minutes after the termination of the previous task use the fixedDelay
member. For example:
Fixed Delay Example
@Scheduled(fixedDelay = "5m")
void fiveMinutesAfterLastExecution() {
System.out.println("Executing fiveMinutesAfterLastExecution()");
}
Fixed Delay Example
@Scheduled(fixedDelay = "5m")
void fiveMinutesAfterLastExecution() {
println "Executing fiveMinutesAfterLastExecution()"
}
Fixed Delay Example
@Scheduled(fixedDelay = "5m")
internal fun fiveMinutesAfterLastExecution() {
println("Executing fiveMinutesAfterLastExecution()")
}
Scheduling a Cron Task
To schedule a Cron task use the cron
member:
Cron Example
@Scheduled(cron = "0 15 10 ? * MON")
void everyMondayAtTenFifteenAm() {
System.out.println("Executing everyMondayAtTenFifteenAm()");
}
Cron Example
@Scheduled(cron = "0 15 10 ? * MON")
void everyMondayAtTenFifteenAm() {
println "Executing everyMondayAtTenFifteenAm()"
}
Cron Example
@Scheduled(cron = "0 15 10 ? * MON")
internal fun everyMondayAtTenFifteenAm() {
println("Executing everyMondayAtTenFifteenAm()")
}
The above example runs the task every Monday morning at 10:15AM in the time zone of the server.
Scheduling with only an Initial Delay
To schedule a task so it runs once after the server starts, use the initialDelay
member:
Initial Delay Example
@Scheduled(initialDelay = "1m")
void onceOneMinuteAfterStartup() {
System.out.println("Executing onceOneMinuteAfterStartup()");
}
Initial Delay Example
@Scheduled(initialDelay = "1m")
void onceOneMinuteAfterStartup() {
println "Executing onceOneMinuteAfterStartup()"
}
Initial Delay Example
@Scheduled(initialDelay = "1m")
internal fun onceOneMinuteAfterStartup() {
println("Executing onceOneMinuteAfterStartup()")
}
The above example only runs once, one minute after the server starts.