在我正在开发的JSF-2应用程序中,当用户执行操作时,我需要启动一个服务器端计时器。
此计时器必须与应用程序本身相关,因此它必须在用户会话关闭时存活。
为了解决这个问题,我想使用java.util.Timer类来实例化Application作用域bean中的timer对象。
这可能是一个好的解决方案吗?有没有其他更好的方法来实现这一点?谢谢
发布于 2012-12-07 20:38:13
否ejb-容器
如果您的容器没有ejb功能(tomcat、jetty等),您可以使用quartz调度器库:http://quartz-scheduler.org/
他们还有一些很好的代码示例:http://quartz-scheduler.org/documentation/quartz-2.1.x/examples/Example1
EJB3.1
如果您的应用服务器安装了EJB3.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);
}
}https://stackoverflow.com/questions/13762723
复制相似问题