background image

The timersession Example

<< Canceling and Saving Timers | Building the timersession Example >>
<< Canceling and Saving Timers | Building the timersession Example >>

The timersession Example

attributes, the EJB container begins the new transaction before calling the @Timeout method. If
the transaction is rolled back, the container will call the @Timeout method at least one more
time.
The timersession Example
The source code for this example is in the
tut-install/javaeetutorial5/examples/ejb/timersession/timersession-ejb/src/java/
directory.
TimerSessionBean
is a stateless session bean that shows how to set a timer. In the source code
listing of TimerSessionBean that follows, note the createTimer and @Timeout methods.
Because it's a business method, createTimer is defined in the bean's remote business interface
(TimerSession) and can be invoked by the client. In this example, the client invokes
createTimer
with an interval duration of 30,000 milliseconds. The createTimer method
creates a new timer by invoking the createTimer method of TimerService. A TimerService
instance is injected by the container when the bean is created. Now that the timer is set, the EJB
container will invoke the timeout method of TimerSessionBean when the timer expires, in
about 30 seconds. Here's the source code for the TimerSessionBean class:
package com.sun.tutorial.javaee.ejb;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerService;
@Stateless
public class TimerSessionBean implements TimerSession {
@Resource
TimerService timerService;
private static final Logger logger = Logger
.getLogger(
"com.sun.tutorial.javaee.ejb.
timersession.TimerSessionBean
");
public void createTimer(long intervalDuration) {
Timer timer = timerService.createTimer(intervalDuration,
"Created new timer");
}
@Timeout
public void timeout(Timer timer) {
logger.info(
"Timeout occurred");
Using the Timer Service
Chapter 22 · Session Bean Examples
671