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

2024-05-13

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


没有 ejb 容器

如果您的容器没有 ejb 功能(tomcat、jetty 等),您可以使用quartz 调度程序库:http://quartz-scheduler.org/ http://quartz-scheduler.org/

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

EJB 3.1

如果您的应用程序服务器有 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);
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JSF-2 应用程序中的服务器端计时器 的相关文章

随机推荐