@Retention(value=RUNTIME) @Target(value=METHOD) public @interface Scheduled
trigger annotation. The trigger defines the way in which the method will be scheduled.
Possible triggers are:
SimpleTrigger - Define a delay or rate at which the method should be
scheduled.CronTrigger - Define a complex cron job pattern to define the
periodicity.DelayedTrigger - Method will be executed only once after a provided
delay.TriggerStrategy using Java's Service
Provider Interfaces.Injector.
WARNING: You should only ever schedule methods in classes bound as Singleton! Otherwise you will prevent scoped objects from being garbage collected and cause a memory leak.
Methods are scheduled by using an implementation of ScheduledExecutorService.
You can provide a Key that will be used to look up the scheduler implementation
on a per-method basis.
BindingAnnotation including Named on the method to
specify the annotation part of the Key.Scheduler to specify the class part of the Key.
@Scheduled
@SimpleTrigger(5000) // execute every 5 seconds
@Named("mainScheduler")
@Scheduler(AdvancedScheduler.class)
public void compute() {...}
In this case, the Scheduler to use will be looked up like
injector.getInstance(Key.get(AdvancedScheduler.class,
Names.named("mainScheduler"))
If you leave out the Scheduler part, the class defaults to
ScheduledExecutorService.class. If you leave out the binding annotation, the
created key will not have an annotation part. If you put neither a binding annotation
nor a Scheduler class on the method, a default ScheduledExecutorService is used which
is created internally. You should make no assumptions about the actual behavior of that
service and it is highly recommended to bind and specify an ScheduledExecutorService
yourself.
public class MyModule extends AbstractModule {
@Provides
public ThreadFactory provideMyThreadFactory() {
return new ThreadFactoryBuilder()....build(); // class from Google guava
}
@Provides
@Named("mainScheduler")
public ScheduledExecutorService provideMyExecutor(ThreadFactory threadFactory) {
return Executors.newScheduledThreadPool(NUM_OF_THREADS, threadFactory);
}
}
The framework will take care of injecting all parameters of a scheduled method when it
is being executed. The injected objects are retrieved from the Injector right
before every execution of the method.
@Scheduled
@SimpleTrigger(5000) // execute every 5 seconds
public void compute(ComputationService service,
@Named("threshold") int computationThreshold) {...}
As your method is executed asynchronously, special care has to be taken to ensure thread safety of that operation. Beware of the following:
Scheduled methods can throw checked exceptions. If they do, those exceptions will be
delegated to the ExceptionHandler in place. You can specify a custom handler
for a scheduled method using the OnError annotation. If you do not specify a
handler, a default handler which prints a log message will be used.
Copyright © 2014–2018. All rights reserved.