WAS v8.5 > Reference > Command-line utilities

Example: Using the Timer Service with the TimedObject interface

This example shows the implementation of the ejbTimeout() method that is called when the scheduled event occurs.

Best practice: The EJB 3.x programming model provides additional strategic ways to define persistent and non-persistent timers within your business environments. Although defining persistent timers using the ejbTimeout method with the TimedObject interface is still supported, take advantage of the easy-to-implement EJB annotations to create persistent and non-persistent timers to meet your business needs. See the using the EJB timer service for enterprise beans information to learn more about creating persistent and non-persistent timers using annotations or defining our own timeout methods within a deployment descriptor.

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 the 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


Configure a timer service for network deployment


Related information:

EJB timer service settings


+

Search Tips   |   Advanced Search