Example: Timer Service

This example shows the implementation of the ejbTimeout() method that is called when the scheduled event occurs. The ejbTimeout method can contain any code normally placed in a business method of the bean. Method level attributes such as transaction or runAs can be associated with this method by the application assembler. An instance of the Timer object that causes the method to fire is passed in as an argument to ejbTimeout().

import javax.ejb.Timer;
import javax.ejb.TimedObject;
import javax.ejb.TimerService;

public class MyBean implements EntityBean, TimedObject {

  // This method is called by the EJB container upon Timer expiration.
  public void ejbTimeout(Timer theTimer) {

    // Any code typically placed in an EJB method can be placed here.

     String whyWasICalled = (String) Timer.getInfo():
     System.out.println("I was called because of"+ whyWasICalled);
  } // end of method ejbTimeout

In this section, a Timer is created that executes the ejbTimeout() method in 30 seconds. A simple string object is passed in at Timer creation to identify the Timer.

// instance variable to hold the EJB context.
private EntityContext theEJBContext;

// This method is called by the EJB container upon bean creation.
public void setEntityContext(EntityContext theContext) {

  // save the entity context passed in upon bean creation.
  theEJBContext = theContext;

}

// This business method cause the ejbTimeout method to invoke in 30 seconds.
public void fireInThirtySeconds() throws EJBException  {

  TimerService theTimerService = theEJBContext.getTimerService();
  String aLabel = "30SecondTimeout";
  Timer theTimer = theTinmerService.createTimer(30000, aLabel);

} // end of method fireInThirtySeconds

} // end of class MyBean