Java Reference
In-Depth Information
Table 5-2. Programmatic TimerService Methods for Timer Creation
Creates a calendar timer based upon the input schedule expression.
Creates an interval timer whose first expiration occurs at a given point in time or
duration and whose subsequent expirations occur after a specified interval.
Creates a single-action timer that expires after a specified period of time or duration.
Creates a timer whose type depends upon the parameters that are passed to the
createTimer method.
The following excerpt, taken from org.javaee7.jpa.session.AcmeTimerFacade , demonstrates how to create
a programmatic timer that will expire in 6,000 milliseconds:
public String createProgrammaticTimer() {
long duration = 6000;
Timer timer = timerService.createTimer(duration, "Created new programmatic timer");
return "TimerExamples"; // Used for Navigation
When creating a programmatic timer, such as demonstrated in the previous example, the method within the
bean that is annotated with @Timeout will be invoked when the programmatic timer expires and then again upon
each duration expiration. The following code demonstrates an example of one such method that will be invoked
when a bean's programmatic timer expires:
public void timeout(Timer timer){
System.out.println("The timer was just invoked...");
To schedule a timer based upon a given calendar time and date, annotate the session bean method that you want
to invoke with the @Schedule annotation, which was introduced in EJB 3.1. The following method demonstrates a
timer that will expire every minute:
@Schedule(minute="*, hour="*")
public void scheduledTimerExample(){
System.out.println("This timer will go off every minute");
In the previous example, the @Schedule annotation accepts two attributes: minute and hour. In the example, the
minute value is indicated by the wildcard character * , meaning that the timer is scheduled to go off every hour
of every minute. Suppose that you have each of these timers (and possibly more) specified within a given
session bean. At any given point it may make sense to check which timers are active. You can do so by calling the
TimerService.getAllTimers method, which returns a Collection of Timer instances. The following method demonstrates
how to obtain all the active timers and build a String that provides the current information for each of them:
public String getTimerInfo(){
Collection<Timer> timers = timerService.getAllTimers();
StringBuffer sb = new StringBuffer();
int x = 0;
Search WWH ::

Custom Search