12.12.11

Simple EJB 3.0 Timer

Creating an EJB 3.0 Timer is pretty straight forward.
First, the TimerService is needed. It can be  retrieved direclty via Dependency Injection or using the SessionContext.

@Resource
private javax.ejb.TimerService timerSerivce;

The TimerService interface offers different methods for the creating the actual timer. Most important is the differentiation between  single-event and interval.

public void doSmg() {
     System.out.println("Create Timer");
     timerSerivce.createTimer(3000,3000,  
                            "ObjectAccessibleInTheTimeoutMethod");
}

The first parameter indicates when the timer goes off; the value must be relative, so in this case it will be executed in 3 seconds. For details on the method signatures, please refer to the API doc.
Within the same Bean a method with the following signature and annotation is needed:

@Timeout
 public void timeSomething(Timer timer) {
        System.out.println(timer.getInfo());
 }

It is executed whenever the timer goes off. The getInfo() method returns the passed serializable Object, in this case the String "ObjectAccessibleInTheTimeoutMethod".

Timer Facts:
  • Timers are persistent by specification, if the server crashes or is shutdown, created timers must still exist. However, just to get sure check your server's documentation, e.g. older JBoss servers versions delete timers after  a shutdown. Furthermore, the persisting - implementation is not specified, so this can vary too.
  • If the execution of a timer was missed, because e.g. the server was shut down, it will immediately be called after the server is back online.
  • The timer methods (annotated with @Timeout) are execeuted within a transaction.
  • Possible just for Message Driven and Stateless Session Beans

No comments:

Post a Comment