EJB Timer Service

The Timer Service can be used to build applications that depends on time based services. In this tutorial we will show how you can receive timer notifications on your Stateless Session Beans.

The EJB @Timeout annotation makes it easy to program an EJB timer service in your bean class. The EJB timer service is an EJB-container provided service that allows you to create timers that schedule callbacks to occur when a timer object expires.

Previous to EJB 3.0, your bean class was required to implement javax.ejb.TimedObject if you wanted to program the timer service. Additionally, your bean class had to include a method with the exact name ejbTimeout. These requirements are relaxed in Version 3.0 of EJB. You no longer are required to implement the javax.ejb.TimedObject interface, and you can name your timeout method anything you want, as long as you annotate it with the @Timeout annotation. You can, however, continue to use the pre-3.0 way of programming the timer service if you want.


We will show here an example:
Create a new Stateless Bean named TimerSampleBean and its remote interface TimerSample
package com.sample;

import java.util.Date;
import javax.annotation.Resource;
import javax.ejb.*;

@Stateless

public class TimerSampleBean implements TimerSample
{
   private @Resource SessionContext ctx;

   public void scheduleTimer(long milliseconds)
   {
      ctx.getTimerService().createTimer(new Date(new Date().getTime() + milliseconds), "Hello World");
   }

   @Timeout
   public void timeoutHandler(Timer timer)
   {
      System.out.println("---------------------");
      System.out.println("* Received Timer event: " + timer.getInfo());
      System.out.println("---------------------");

      timer.cancel();
   }
}

package com.sample; 
import javax.ejb.Remote; 
@Remote public interface TimerSample { 
    void scheduleTimer(long milliseconds); 
}
As you can see, the timer is scheduled in the schedulerTimer method :
public void scheduleTimer(long milliseconds)  {
      ctx.getTimerService().createTimer(new Date(new Date().getTime() + milliseconds), "Hello World");
}

An enterprise bean schedules itself for a timed notification using a reference to the TimerService , which can be obtained from the EJBContext or injected directly into your bean using the @javax.annotation.Resource annotation. The TimerService allows a bean to register itself for notification on a specific date, after some period of time, or at recurring intervals.
 
The notification is handled in the timeoutHandler method which receives as argument an instance of the Timer object:
@Timeout
   public void timeoutHandler(Timer timer)
   {
      System.out.println("---------------------");
      System.out.println("* Received Timer event: " + timer.getInfo());
      System.out.println("---------------------");
      timer.cancel();
   }

As you can see, after the notification has been acquired, the timer is cancelled, otherwise the notification would repeat at regual intervals.

Building the Client

Building a Test client doesn't require anything else then looking up the SLSB and invoking the method scheduleTimer which schedules the timeout handler after 5000 ms:
import java.util.Hashtable;
import javax.naming.InitialContext;

public class TestClient {
    public static void main(String[] args) throws Exception
       {
        Hashtable ht=new Hashtable();   
        ht.put(InitialContext.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
        ht.put(InitialContext.PROVIDER_URL,"jnp://localhost:1099");   
        ht.put(InitialContext.URL_PKG_PREFIXES,"org.jboss.naming:org.jnp.interfaces");
         

        InitialContext ctx = new InitialContext(ht);
         
          TimerSample timer = (TimerSample) ctx.lookup("TimerSampleBean/remote");
          timer.scheduleTimer(5000);
       }

}
Single actions timers and Interval timers

In the above example we are scheduling a timer after 5000 ms. In such a scenario the timer would repeat its scheduling until the cancel method is called.
You can, however, schedule a timer for a single action. For his purpose you have two distinct createTimer methods:

createTimer(Date expiration, Serializable info)

Creates a single-action timer that expires once. The timer expires on the date set for the expiration parameter. Here's how to set a timer that expires on November 4, 2009:

Calendar calender = Calendar.getInstance( );
calendar.set(2009, Calendar.NOVEMBER, 4);
timerService.createTimer(calendar.getTime( ), null);

createTimer(long duration, Serializable info)

Creates a single-action timer that expires only once. The timer expires after duration time (measured in milliseconds) has elapsed. Here's how to set a timer that expires in 30 days:
long thirthyDays = 1000 * 60 * 60 * 24 * 30; // 30 days
timerService.createTimer(thirthyDays, null);
Developers can take the advantage of the EJB Timer Services for building robust scheduling applications. If you however need a more complex strategy for your Enterpirse applications I would suggest having a look at a Quartz tutorial:

Related articles available on mastertheboss.com

EJB 3.0 tutorial : Session Beans

Enterprise JavaBeans (EJB) technology is a J2EE technology for de

JBoss MDB 3.0

Message-driven beans (MDBs) are stateless, server-side, transacti

JBoss EJB 3 BMT

In a Bean Managed Transaction, the code in the session or message

How do you keep your EJB callbacks separated from biz. methods?

JBoss daily recipe

How to set EJB timeout period ?

JBoss recipe of the day

How to add a Selector with MDB 3.0 ?

Message selectors allow an MDB to be more selective about the mes

Follow us on Twitter