JSF-2应用程序中的服务器端计时器 [英] Server side timer in a JSF-2 application
问题描述
在我正在处理的JSF-2应用程序中,我需要在用户执行操作时启动服务器端Timer.
此计时器必须与应用程序本身相关,因此在关闭用户会话时必须保留该计时器.
为了解决此问题,我认为可以使用java.util.Timer类在Application范围的Bean中实例化计时器对象.
会是一个好的解决方案吗?还有其他更好的方法可以做到这一点吗?谢谢
in the JSF-2 application I'm working on, I need to start a server side Timer when a user does an action.
This timer must be related to the application itself, so it must survive when the user session is closed.
To solve this problem, I thought to use java.util.Timer class instantiating the timer object in an Application scoped bean.
Could it be a good solution? Are there other better ways to achive this? Thanks
推荐答案
没有ejb容器
如果您的容器不具有ejb功能(tomcat,码头等),则可以使用石英调度程序库: http ://quartz-scheduler.org/
If your container doesnt have ejb capabilities (tomcat, jetty etc..), you can go with quartz scheduler library: http://quartz-scheduler.org/
他们还有一些不错的代码示例: http://quartz- scheduler.org/documentation/quartz-2.1.x/examples/Example1
They also has some nice code samples: http://quartz-scheduler.org/documentation/quartz-2.1.x/examples/Example1
EJB 3.1
如果您的应用程序服务器具有EJB 3.1(glassfish,Jboss),则存在Java ee标准的创建计时器的方法.主要查看@Schedule和@Timeout批注.
If your app-server have a EJB 3.1 (glassfish, Jboss), there is a java ee standard way of creating timers. Mainly look into the @Schedule and @Timeout annotations.
类似的情况可能会覆盖您的用例(注释为@Timeout的方法将在计时器用尽时被调用)
Something like this might cover your usecase (method annotated @Timeout will be invoked when timer runs out)
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);
}
}
这篇关于JSF-2应用程序中的服务器端计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!