示例:将计时器服务用于 TimedObject 接口
此示例显示在预定事件发生时调用的 ejbTimeout() 方法的实现。

EjbTimeout 方法可以包含通常位于 Bean 的业务方法中的任何代码。应用程序组装者可以使方法级别属性(例如 transaction 或 runAs)与此方法相关联。会引起 ejbTimeout 方法触发的 Timer 对象的实例作为参数传递至该方法。
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
创建在 30 秒内启动 ejbTimeout 方法的 Timer。 Timer 创建期间会传递简单的字符串对象来标识 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;
} // end of method setEntityContext
// 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