Discussions

EJB design: Servlet context destroyed and EJB timer session bean

  1. Hi, I have a EJB 3.0 stateless session bean that starts a timer service when the server starts (by invoking the bean in a ContextInitialized event of the class that implements ServletContextListener). I want to cancel this timer when the server is stopped. So I put the call to cancel the timer in the ContextDestroyed event. But it doesn't find any timers. The same call to cancel the bean works perfectly if I do it in contextinitialized event or anywhere else. It just doesn't work in ContextDestroyed event. Is this because the sessioncontext is not available in contextdestroyed event? Please help. I have posted my code here: timer bean: public class NotificationTimerBean implements NotificationTimer { private SessionContext ctx; @EJB private EBDataFacade ebDataFacade; public void setSessionContext(SessionContext sc){ ctx = sc; } public void startTimer(String timerName) { ctx.getTimerService().createTimer(300000, 300000, timer); } public void cancelTimer() { try { TimerService ts = sc.getTimerService(); Collection timers = ts.getTimers(); Iterator it = timers.iterator(); while (it.hasNext()) { /*This part is not hit during execution*/ Timer notificationTimer = (Timer) it.next(); notificationTimer.cancel(); } .... Servlet Context Listener Client: public class ApplicationStartupListener implements ServletContextListener { @EJB private static NotificationTimer nTimer; public void contextInitialized(ServletContextEvent event) { try{ log.info("startup.info.notification.timer.lookup"); InitialContext ctx = new InitialContext(); nTimer = (NotificationTimer)ctx.lookup("NotificationTimer"); // TODO: Move this to ContextDestroyed nTimer.cancelTimer("Notification Expiry Timer"); nTimer.startTimer("Notification Expiry Timer"); } catch (NamingException e) { e.printStackTrace(); } public void contextDestroyed(ServletContextEvent event) { nTimer.cancelTimer(); }
  2. I ran into the same issue. Does anyone have an answer?