-
Notifications
You must be signed in to change notification settings - Fork 4
Scheduled methods
A method can be marked with @Scheduled
to have its execution scheduled at a certain periodicity. The periodicity is specified by an additional trigger annotation. For example you can use a @CronTrigger
for defining complex scheduling plans:
@Scheduled
@Crontrigger("0 0 12 ? * WED") // execute every wednesday at 12pm
public void scheduleMethod() {
// do something
}
A method is scheduled according to its trigger annotation by the time an object of its containing type is constructed by the Injector
. If the annotation is placed on a static
method, it is scheduled by the time its type is encountered by the Injector.
In contrast to asynchronous methods, scheduled methods can be final
or private
because scheduling does not involve AOP techniques for interception.
WARNING: You should only ever schedule methods from within Singleton scoped objects. Otherwise you will run into memory leaks because the scheduler will keep a reference to the instance on which the scheduled method is to be called. (There might be an exception to this, see Cancellation)
As seen above scheduling a method requires a trigger which defines the scheduling behavior. While you can write your own trigger strategies the framework comes with three default implementations.
This trigger schedules methods in terms of the scheduling API provided by Java's ScheduledExecutorService
. For example:
@Scheduled
@SimpleTrigger(value = 5, initialDelay = 5, timeUnit = TimeUnit.MINUTES, scheduleType = ScheduleType.AT_FIXED_RATE)
public void scheduledMethod() {
}
All fields except value
are optional and have sensible defaults.
Schedules a method to be executed only once after a certain delay and then forgets about it.
@Scheduled
@DelayedTrigger(value = 5, timeUnit = TimeUnit.SECONDS)
public void scheduledMethod() {
}
This trigger allows for complex execution plans using cron patterns. The framework uses cron-utils for evaluating cron patterns in Quartz format. Please refer to the mentioned links for information on how to build valid cron patterns.
@Scheduled
@Crontrigger("0 0 12 ? * WED") // execute every wednesday at 12pm
public void scheduleMethod() {
// do something
}