JSF-2应用程序中的服务器端计时器

在我正在研究的JSF-2应用程序中,我需要在用户执行操作时启动服务器端Timer。
此计时器必须与应用程序本身相关,因此它必须在用户会话关闭时继续存在。
为了解决这个问题,我想使用java.util.Timer类来实例化Application scoped bean中的timer对象。
这是一个很好的解决方案吗? 还有其他更好的方法来实现这个目标吗? 谢谢

没有ejb容器

如果你的容器没有ejbfunction(tomcat,jetty等……),你可以使用quartz调度程序库: http : //quartz-scheduler.org/

他们还有一些很好的代码示例: http : //quartz-scheduler.org/documentation/quartz-2.1.x/examples/Example1

EJB 3.1

如果您的app-server有EJB 3.1(glassfish,Jboss),那么有一种java ee标准的创建计时器的方法。 主要研究@Schedule和@Timeout注释。

这样的事情可能会覆盖你的用例(当计时器用完时,将调用注释@Timeout的方法)

import javax.annotation.Resource; import javax.ejb.Stateless; import javax.ejb.Timeout; import javax.ejb.Timer; import javax.ejb.TimerConfig; import javax.ejb.TimerService; @Stateless public class TimerBean { @Resource protected TimerService timerService; @Timeout public void timeoutHandler(Timer timer) { String name = timer.getInfo().toString(); System.out.println("Timer name=" + name); } public void startTimer(long initialExpiration, long interval, String name){ TimerConfig config = new TimerConfig(); config.setInfo(name); config.setPersistent(false); timerService.createIntervalTimer(initialExpiration, interval, config); } }