The Java EE 5 Tutorial

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");
    }
}

Note –

Application Server has a default minimum timeout value of 7000 milliseconds, or 7 seconds. If you need to set the timeout value lower than 7000 milliseconds, change the value of the minimum-delivery-interval-in-millis element in domain-dir/config/domain.xml. Due to virtual machine constraints, the lowest practical value for minimum-delivery-interval-in-millis is around 10 milliseconds.