Skip to content

Scopes and context

Simon Taddiken edited this page Mar 22, 2018 · 2 revisions

Every method which is being scheduled is assigned a unique ScheduledContext. If the same method is scheduled multiple times (because the Injector created multiple instances of its owning type), a new context is created for each instance.

Every time a scheduled method is actually invoked by the framework, this invocation is assigned a ExecutionContext. This context invalidates as soon as the current invocation returns.

Prior to each invocation, the framework assigns the respective context objects to a ThreadLocal of the executing thread. During execution of a scheduled method the current ScheduledContext can be obtained by calling ScheduledCotnextHolder.getContext(). The current ExecutionContext can be obtained by calling ScheduledContextHolder.getContext().getExecution().

Instead of refering to the static accessors you should prefer to inject the scope objects.

@Scheduled
@SimpleTrigger(2000)
public void scheduledMethod(ScheduledContext scheduledContext, ExecutionContext execution) {

}

Both contexts are bound as scoped proxy thus allowing you to inject them directly into singleton scoped types. However, calling any methods on the injected object require an execution to be active for the current thread.

Scopes

Both contexts maintain a map of objects which is used to build custom scopes for storing instances. If you bind a type in ExecutionScope it pertains for a single execution and will be recreated each time the method is invoked. If you bind a type in ScheduledScope it pertains for every execution of one scheduled method.