background image

Canceling and Saving Timers

<< Using the Timer Service | The timersession Example >>
<< Using the Timer Service | The timersession Example >>

Canceling and Saving Timers

Canceling and Saving Timers
Timers can be canceled by the following events:
When a single-event timer expires, the EJB container calls the @Timeout method and then
cancels the timer.
When the bean invokes the cancel method of the Timer interface, the container cancels the
timer.
If a method is invoked on a canceled timer, the container throws the
javax.ejb.NoSuchObjectLocalException
.
To save a Timer object for future reference, invoke its getHandle method and store the
TimerHandle
object in a database. (A TimerHandle object is serializable.) To re-instantiate the
Timer
object, retrieve the handle from the database and invoke getTimer on the handle. A
TimerHandle
object cannot be passed as an argument of a method defined in a remote or web
service interface. In other words, remote clients and web service clients cannot access a bean's
TimerHandle
object. Local clients, however, do not have this restriction.
Getting Timer Information
In addition to defining the cancel and getHandle methods, the Timer interface defines
methods for obtaining information about timers:
public long getTimeRemaining();
public java.util.Date getNextTimeout();
public java.io.Serializable getInfo();
The getInfo method returns the object that was the last parameter of the createTimer
invocation. For example, in the createTimer code snippet of the preceding section, this
information parameter is a String object with the value created timer.
To retrieve all of a bean's active timers, call the getTimers method of the TimerService
interface. The getTimers method returns a collection of Timer objects.
Transactions and Timers
An enterprise bean usually creates a timer within a transaction. If this transaction is rolled back,
the timer creation is also rolled back. Similarly, if a bean cancels a timer within a transaction
that gets rolled back, the timer cancellation is rolled back. In this case, the timer's duration is
reset as if the cancellation had never occurred.
In beans that use container-managed transactions, the @Timeout method usually has the
Required
or RequiresNew transaction attribute to preserve transaction integrity. With these
Using the Timer Service
The Java EE 5 Tutorial · September 2007
670