示例:将计时器服务用于 TimedObject 接口
此示例显示在预定事件发生时调用的 ejbTimeout() 方法的实现。
最佳实践: EJB 3.x 编程模型提供其他战略方法来定义企业环境中的持续性和非持续性计时器。虽然仍然支持使用带有 TimedObject 接口的 ejbTimeout 方法来定义持久性计时器,但是还是应该利用易于实现的 EJB 注释来创建持久性和非持久性计时器以满足您的业务需要。请参阅使用企业 Bean 的 EJB 计时器服务信息,了解更多关于使用注释创建持久和非持久性计时器或定义部署描述符内的超时方法的信息。bpracEjbTimeout 方法可以包含通常位于 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
参考主题