Java Reference
In-Depth Information
When the application code invokes the setTimer method, it creates a single‐action timer that
calls a “timeout” method in the same bean after the specii ed duration of 30,000 milliseconds.
A “timeout” method is identii ed by the annotation @Timeout and must conform to certain
requirements. It must not throw exceptions or return a value. It's also exempt from needing to take
a parameter, but if it does, it must be of type javax.ejb.Time . There can be only one “timeout”
method.
@Timeout
public void performTask() {
System.out.println("Simple Task performed");
}
The Context Dependency Injection (CDI) container injects a reference to the TimerService
into an instance variable annotated @Resource . Here the container injects the instance variable
timerService .
@Resource
TimerService timerService;
If you put together the previous three code snippets into a single bean and the application code
calls the setTimer method, you create a timer that, after 30 seconds, calls the “timeout” method
performTask . Listing 10‐2 shows the simplest possible implementation of the programmatic timer
in Java EE 7.
LISTING 10‐2: The simplest implementation of a programmatic timer
package com.devchronicles.timer;
import javax.annotation.Resource;
import javax.ejb.Timeout;
import javax.ejb.TimerService;
public class SimpleProgrammaticTimer {
@Resource
TimerService timerService;
public void setTimer(){
timerService.createTimer(30000, "New timer");
}
@Timeout
public void performTask() {
System.out.println("Simple Task performed");
}
}
There are four timer creation methods in the TimerService interface with ten signatures.
Table 10-2 shows an example of each one:
Search WWH ::




Custom Search