Message-Driven Bean Timers

Message-driven bean timers are similar to stateless session bean timers in several ways: timers are associated only with the type of bean. When a timer expires, a message-driven bean instance is selected from a pool to execute the ejbTimeout( ) method. In addition, message-driven beans can be used for performing audits or other types of batch jobs. The primary difference between a message-driven bean timer and a stateless session bean timer is the way in which they’re initiated: timers are created in response to an incoming message or, if the container supports it, from a configuration file.

In order to initialize a message-driven bean timer from an incoming message, simply put the call to the TimerService.createTimer( ) method in the message-handling method. For a JMS-based message-driven bean, the method call goes in the onMessage( ) method:

public class JmsTimerBean 
      implements javax.ejb.MessageDrivenBean, javax.ejb.TimedObject {
    
    public void onMessage(Message message){
        MapMessage mapMessage = (MapMessage)message;
        long expirationDate = mapMessage.getLong("expirationDate");
        
        TimerService timerService = ejbContext.getTimerService( );
        timerService.createTimer(expirationDate, null );
                   }
    
    public void ejbTimeout( ){
        // put timeout logic hear
    }

The incoming JMS message should contain information about the timer: the beginning (start) date, duration, or even the serializable info object. Combining JMS with the Timer Service can offer some powerful design options ...

Get Enterprise JavaBeans, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.