| Oracle® Containers for J2EE Enterprise JavaBeans Developer's Guide 10g (10.1.3.1.0) Part Number B28221-02 |
|
|
View PDF |
You can configure the following types of enterprise beans to use a Java EE timer:
EJB 3.0 stateless session beans and message-driven beans.
EJB 2.1 stateless session beans, entity beans with container-managed persistence, entity beans with bean-managed persistence, and message-driven beans.
To configure an enterprise bean with a Java EE timer, do the following:
Acquire the javax.ejb.TimerService in one of the following ways:
For an EJB 3.0 enterprise bean, use the @Resource annotation, as Example 25-1 shows.
For an EJB 3.0 or EJB 2.1 enterprise bean, use EJBContext or InitalContext method getTimerService, as Example 25-2 shows.
Use TimerService method createTimer to create the appropriate type of timer (see the javax.ejb.TimerService API), as Example 25-1 and Example 25-2 show.
When you create a Timer on an EJB 2.1 entity bean, the container invokes the timeout callback method of that particular entity bean instance identified by its primary key. Timers created for a particular entity bean are removed when the entity bean is removed.
When you create a Timer on any other type of enterprise beans, the container invokes the timeout callback method on any instance of that type in the pooled state.
Implement a timeout callback method.
This method must not be static or final and must have the following signature:
void <METHOD>(Timer timer)
You can implement a timeout callback method in one of the following ways:
For an EJB 3.0 enterprise bean, annotate any bean method using the @Timeout annotation, as Example 25-1 shows.
For an EJB 3.0 or EJB 2.1 enterprise bean, implement the javax.ejb.TimedObject interface, as Example 25-2 shows.
Example 25-1 Configuring a Java EE Timer on an EJB 3.0 Stateless Session Bean
import javax.ejb.Stateless;
import javax.annotation.PostConstruct;
import javax.ejb.TimerService;
import javax.ejb.Timer;
import javax.ejb.Timeout;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
@Stateless
public class MySession {
@PostConstruct
@TransactionAttribute(value=REQUIRES_NEW)
public void initialize() {
@Resource TimerService timerService;
Timer timer = ts.createTimer(timeout, "Optional-Serializable-Info");
}
...
@Timeout
@TransactionAttribute(value=REQUIRES_NEW)
public void timeoutCallback(Timer timer) {
...
}
}
Example 25-2 Configuring a Java EE Timer on an EJB 2.1 Stateless Session Bean
import javax.ejb.SessionBean;
import javax.ejb.TimerService;
import javax.ejb.TimedObject;
public class MySession implements SessionBean, TimedObject {
public void initialize() {
InitialContext ctx = new InitialContext();
TimerService ts = ctx.getTimerService();
Timer timer = ts.createTimer(timeout, "Optional-Serializable-Info");
}
...
public void ejbTimeout(Timer timer) {
...
}
}