+

Search Tips   |   Advanced Search

Example: Using the 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 that is typically 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 method.

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) theTimer.getInfo():
     System.out.println("I was called because of"+ whyWasICalled);
  } 
// end of method ejbTimeout

A Timer is created that starts 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 causes the ejbTimeout method to begin in 30 seconds. 
public void fireInThirtySeconds() throws EJBException  {

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

} 
// end of method fireInThirtySeconds

} 
// end of class MyBean




 

Related tasks


Set a timer service for network deployment

 

Related information


EJB timer service settings