Java Reference
In-Depth Information
7.1.4. Timer interface
When you schedule a delayed invocation on a bean, you're creating a timer. A timer knows
when it's going to go off and what method it's going to invoke. Therefore, when you create
timers, you provide the container with two pieces of information: a configuration setting
defining when you want the timer to complete and a method, known as a time-out, to in-
voke when the timer completes. The container uses this information to create a timer. How
the timer is implemented is up to the container provider—implementing timers robustly is
obviously not trivial.
As you'll see, there are three ways to configure timers: with annotations, programmatically,
or via configuration files. Individual timers can be manipulated via the
javax.ejb.Timer
interface shown in
listing 7.1
. This interface provides you with one
operation,
cancel
, and several methods for retrieving various pieces of information about
the timer. To get a representation of a timer that can be serialized, use the
getHandle()
method. This method returns a
javax.ejb.TimerHandle
, which can be used to re-
trieve the timer instance. The
TimerHandle
is valid only within the container—it can't
be passed to remote code. Information on the timer, passed in when creating the timer, can
be retrieved with the
getInfo()
method. This can be any serialized object but will be
a string if you're using the
info
attribute on the
Schedule
annotation. The
getNex-
tTimeout()
will return a
Date
object with the time of the next time-out. Note that by
the time you check it, the timer may have already fired. The
getSchedule()
returns a
javax.ejb.ScheduleExpression
with the scheduling information for cron-based
timers. The
getTimeRemaining()
returns the number of milliseconds that will elapse
before the timer fires again. The
isCalendarTimer()
returns true if this timer is a
cron-based timer. Finally, the last method on the interface,
isPersistent()
, returns
true if this timer will survive server restarts/failures.
Listing 7.1. Specification for the
Timer
interface
public interface Timer {
void cancel();
TimerHandle getHandle();
Serializable getInfo();
Date getNextTimeout();
ScheduleExpression getSchedule();
long getTimeRemaining();
boolean isCalendarTimer();
boolean isPersistent();
}