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 notifications for all
types of enterprise beans, except for stateful session beans. You can schedule a timed noti-
fication to occur according to a calendar schedule either at a specific time, after the dura-
tion of a time period, 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, which contains a method annotated with the
java.ejb.Schedule
or
java.ejb.Schedules
annotations. Let's see both ap-
proaches 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 to get a
TimerService
instance is to use resource injection. For ex-
ample, in the
TheatreBox
singleton EJB, we will use the
@Resource
annotation to in-
ject a
TimerService
object, as shown in the following code snippet:
@Resource
TimerService timerService;
private static final long DURATION =
TimeUnit.SECONDS.toMillis(6);
The duration specifies the time (in milliseconds) when the single timer is fired. The method
that will fire the timer will use the
TimerService
instance to invoke
cre-
ateSingleActionTimer
, passing the duration and an instance of the
TimerConfig
class as an argument, which may optionally contain some basic information (such as the
description of the timer). This is shown in the following code snippet:
public void createTimer(){
timerService.createSingleActionTimer(DURATION, new