EJB timer service

Stateless session beans and message-driven beans can have a method that is executed periodically at regular intervals of time. This can be accomplished by using the EJB timer service. The following example illustrates how to take advantage of this feature:

package net.ensode.javaeebook; 
 
//imports omitted 
 
@Stateless 
public class EjbTimerExampleBean implements EjbTimerExample 
{ 
  private static Logger logger = Logger.getLogger(EjbTimerExampleBean.class  
      .getName());  
  @Resource  
  TimerService timerService;  
 
  public void startTimer(Serializable info)  
  {  
    Timer timer = timerService.createTimer  
      (new Date(), 5000, info);  
  }  
 
  public void stopTimer(Serializable info)  
  {  
    Timer timer;  
    Collection timers = timerService.getTimers();  
 
    for (Object object : timers)  
    {  
      timer = ((Timer) object);  
 
      if (timer.getInfo().equals(info))  
      {  
        timer.cancel();  
        break;  
      }  
    }  
  }  
 
  @Timeout  
  public void logMessage(Timer timer)  
  {  
    logger.info("This message was triggered by :" +  
        timer.getInfo() + " at "  
        + System.currentTimeMillis());  
  }  
} 

In the preceding example, we inject an implementation of the javax.ejb.TimerService interface by decorating an instance variable of this type with the @Resource annotation. We can then create a timer by invoking the createTimer() method of this TimerService instance.

There are several overloaded versions of the createTimer() method. The one we chose to use takes an instance of java.util.Date as its first parameter; this parameter is used to indicate the first time the timer should expire ("trfgo off"). In the example, we chose to use a brand new instance of the Date class, which makes the timer expire immediately. The second parameter of the createTimer() method is the amount of time to wait, in milliseconds, before the timer expires again. In the preceding example, the timer will expire every five seconds. The third parameter of the createTimer() method can be an instance of any class implementing the java.io.Serializable interface. Since a single EJB can have several timers executing concurrently, this third parameter is used to uniquely identify each of the timers. If we don't need to identify the timers, null can be passed as a value for this parameter.

The EJB method invoking TimerService.createTimer() must be called from an EJB client. Placing this call in an EJB method (decorated with the @PostConstruct annotation to start the timer automatically when the bean is placed in the Ready state) will result in an IllegalStateException being thrown.

We can stop a timer by invoking its cancel() method. There is no way to directly obtain a single timer associated with an EJB; what we need to do is invoke the getTimers() method on the instance of TimerService that is linked to the EJB. This method will return a collection containing all the timers associated with the EJB; we can then iterate through the collection and cancel the correct one by invoking its getInfo() method. This method will return the Serializable object we passed as a parameter to the createTimer() method.

Finally, any EJB method decorated with the @Timeout annotation will be executed when a timer expires. Methods decorated with this annotation must return void and take a single parameter of type javax.ejb.Timer. In our example, the method simply writes a message to the server log.

The following class is a standalone client for the preceding EJB:

package net.ensode.javaeebook; 
 
import javax.ejb.EJB; 
 
public class Client 
{ 
  @EJB  
  private static EjbTimerExample ejbTimerExample;  
 
  public static void main(String[] args)  
  {  
    try  
    {  
      System.out.println("Starting timer 1...");  
      ejbTimerExample.startTimer("Timer 1");  
      System.out.println("Sleeping for 2 seconds...");  
      Thread.sleep(2000);  
      System.out.println("Starting timer 2...");  
      ejbTimerExample.startTimer("Timer 2");  
      System.out.println("Sleeping for 30 seconds...");  
      Thread.sleep(30000);  
      System.out.println("Stopping timer 1...");  
      ejbTimerExample.stopTimer("Timer 1");  
      System.out.println("Stopping timer 2...");  
      ejbTimerExample.stopTimer("Timer 2");  
      System.out.println("Done.");  
    }  
    catch (InterruptedException e)  
    {  
      e.printStackTrace();  
    }  
  }  
} 

The example simply starts a timer, waits for a couple of seconds, and then starts a second timer. It then sleeps for 30 seconds and then stops both timers. After deploying the EJB and executing the client, we should see some entries like this in the server log:

    [2013-08-26T20:44:55.180-0400] [glassfish 4.0] [INFO] [] [net.ensode.javaeebook.EjbTimerExampleBean] [tid: _ThreadID=147 _ThreadName=__ejb-thread-pool1] [timeMillis: 1377564295180] [levelValue: 800] [[
    
      This message was triggered by :Timer 1 at 1377564295180]]
    
    
    
    [2013-08-26T20:44:57.203-0400] [glassfish 4.0] [INFO] [] [net.ensode.javaeebook.EjbTimerExampleBean] [tid: _ThreadID=148 _ThreadName=__ejb-thread-pool2] [timeMillis: 1377564297203] [levelValue: 800] [[
    
      This message was triggered by :Timer 2 at 1377564297203]]
    
    
    
    [2013-08-26T20:44:58.888-0400] [glassfish 4.0] [INFO] [] [net.ensode.javaeebook.EjbTimerExampleBean] [tid: _ThreadID=149 _ThreadName=__ejb-thread-pool3] [timeMillis: 1377564298888] [levelValue: 800] [[
    
      This message was triggered by :Timer 1 at 1377564298888]]
    
    
    
    [2013-08-26T20:45:01.156-0400] [glassfish 4.0] [INFO] [] [net.ensode.javaeebook.EjbTimerExampleBean] [tid: _ThreadID=150 _ThreadName=__ejb-thread-pool4] [timeMillis: 1377564301156] [levelValue: 800] [[
    
      This message was triggered by :Timer 2 at 1377564301156]]
  

These entries are created each time one of the timer expires.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.135.225