Java Reference
In-Depth Information
Using the EJB timer service
Applications that model business workflows often rely on timed notifications. The
timer service of the enterprise bean container enables you to schedule timed notific-
ations for all types of enterprise beans, except for stateful session beans. You can
schedule a timed notification to occur according to a calendar schedule either at a
specific time, after a duration of time, or at timed intervals.
There can be two main types of EJB timers:
programmatic timers
and
automatic
timers
. Programmatic timers are set by explicitly calling one of the timer creation
methods of the
TimerService
interface. Automatic timers are created upon the
successful deployment of an enterprise bean that contains a method annotated with
the
java.ejb.Schedule
or
java.ejb.Schedules
annotations. Let's see both
approaches in the following sections.
Programmatic timer creation
To create a timer, the bean invokes one of the create methods of the
TimerService
interface. These methods allow for either single-action, interval, or calendar-based
timers to be created.
The simplest way of getting a
TimerService
instance is to use resource injection.
For example, in the
TheatreBox
singleton EJB, we will use the
@Resource
an-
notation to inject a
TimerService
object:
@Resource
TimerService timerService;
long duration= 6000;
The duration specifies the time (in ms) when the single timer is fired. The method
that will fire the timer will use the
TimerService
instance to invoke the
cre-
ateSingleActionTimer
, passing the duration and an instance of the
TimerCon-
fig
class as an argument, which may optionally contain some basic information
(such as a description of the timer).