Java Reference
In-Depth Information
In this example, we injected an instance of javax.ejb.TimerService . This class has
methods that allow us to create timers and to obtain a collection of existing timers for
a particular EJB.
We then implemented a method called startTimer() . This method invokes the
createTimer() method in the TimerService instance that was injected into our
EJB. The createTimer() method creates a new timer; there are several overloaded
versions of this method. The one we used in our example has three parameters: the
first parameter is a long value indicating how many milliseconds from the time the
method is invoked should the timer start counting; the second parameter indicates
how many milliseconds before the timer expires; the third parameter is an instance of
java.io.Serializable , which is used as a unique identifier for the created timer.
Consult the Java EE 5 JavaDoc documentation for information on other
versions of the createTimer() method.
Additionally, we created a method called stopTimer() . This method is used to
cancel a specific timer and has a single parameter of java.io.Serializable . Clients
are expected to pass the unique identifier of the timer to cancel as the value of this
parameter. In order to cancel the timer, we first need to obtain all timers for our EJB
via the getTimers() method of TimerService . This method returns a Collection
of javax.ejb.Timer objects. We then need to iterate through this Collection ,
obtain the unique identifier of each Timer object via its getInfo() method, and
compare it to the value of our method's parameter. If they match, we have found the
timer to cancel, and we do so by invoking its cancel() method.
Finally, we defined a method to be invoked when a timer times out. Methods to be
executed when the timer times out must be decorated with the @Timeout annotation,
must be public, return void, and have a single parameter of type Timer . In our
example we simply send some output to the application server log. Notice that part
of the output is the unique identifier for the timer that expired when the method was
invoked, which we can obtain by invoking it's getInfo() method.
Implementing the Client
There is nothing special we need to do to implement a client for an EJB taking
advantage of the EJB timer service. We simply need a client to invoke the methods
that create and cancel the timers. These methods are invoked just like any other EJB
methods defined in a local and/or remote interface.
 
Search WWH ::




Custom Search