background image

Using the Timer Service

<< Testing the Service without a Client | Canceling and Saving Timers >>
<< Testing the Service without a Client | Canceling and Saving Timers >>

Using the Timer Service

Using the Timer Service
Applications that model business work flows 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 notification to
occur at a specific time, after a duration of time, or at timed intervals. For example, you could set
timers to go off at 10:30 AM on May 23, in 30 days, or every 12 hours.
When a timer expires (goes off), the container calls the method annotated @Timeout in the
bean's implementation class. The @Timeout method contains the business logic that handles the
timed event.
The Timeout Method
Methods annotated @Timeout in the enterprise bean class must return void and take a
javax.ejb.Timer
object as the only parameter. They may not throw application exceptions.
@Timeout
public void timeout(Timer timer) {
System.out.println(
"TimerBean: timeout occurred");
}
Creating Timers
To create a timer, the bean invokes one of the createTimer methods of the TimerService
interface. (For details on the method signatures, see the TimerService API documentation at
http://java.sun.com/javaee/5/docs/api/javax/ejb/TimerService.html
.) When the
bean invokes createTimer, the timer service begins to count down the timer duration.
The bean described in
"The timersession Example" on page 671
creates a timer as follows:
Timer timer = timerService.createTimer(intervalDuration,
"Created new timer");
In the timersession example, createTimer is invoked in a business method, which is called by
a client.
Timers are persistent. If the server is shut down (or even crashes), timers are saved and will
become active again when the server is restarted. If a timer expires while the server is down, the
container will call the @Timeout method when the server is restarted.
The Date and long parameters of the createTimer methods represent time with the resolution
of milliseconds. However, because the timer service is not intended for real-time applications, a
callback to the @Timeout method might not occur with millisecond precision. The timer service
is for business applications, which typically measure time in hours, days, or longer durations.
Using the Timer Service
Chapter 22 · Session Bean Examples
669