java - 如何在部署时启动 EJB 计时器?

标签 java jakarta-ee jboss ejb-3.0

我需要创建一个设置为每周自动运行一次的间隔计时器。我不希望它根据用户输入启动,但我希望它在应用程序部署到服务器时创建。我见过的每个例子都有另一个启动计时器的类。我不想使用消息驱动的 bean 来创建计时器,因为审计应该只是在给定时间段内查询数据库,而不是基于发送消息的操作。

我已经包括了一个定时器的例子。在下面的示例中,计时器应每 10 分钟触发一次。作为测试,我希望计时器每 10 分钟触发一次,以便我可以测试计时器。

@Stateless
public class TimerTest implements
        TimerTestLocal, TimerTestRemote{

    @Resource 
    private TimerService timerService;
    private Logger log = Logger.getLogger(TimerTest.class);
    private long interval = 1000 * 60 * 10;
    private static String TIMER_NAME = "AuditTimer";

    public void scheduleTimer() throws NamingException {
        // TODO Auto-generated method stub
        Calendar cal = Calendar.getInstance();
        //cal.set(Calendar.HOUR_OF_DAY, 23);//run at 11pm
        //cal.set(Calendar.MINUTE, 00);
        //cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm");
        log.debug("schedule for: " + sdf.format(cal.getTime()));

        timerService.createTimer(cal.getTime(), interval, TIMER_NAME);
    }

    public void cancelTimer() {
        for(Object obj : timerService.getTimers())
        {
            Timer timer = (Timer)obj;
            if(timer.getInfo().equals(TIMER_NAME))
                timer.cancel();
        }
    }

    @Timeout
    public void timerEvent(Timer timer) {
        log.debug("timer fired");
    }


}

那么有什么方法可以在部署应用程序时启动这个计时器吗?我认为将 Timer 的创建放在 @PostConstruct 方法中不是一个好主意,因为服务器中有类加载器。

最佳答案

如果您的项目可以使用 jee6/ejb3.1,那么这个问题会有更好的解决方案。 http://docs.oracle.com/javaee/6/tutorial/doc/bnboy.html

@javax.ejb.Schedule(minute="*/10", hour="*")
public void automaticTimeout() {
    logger.info("Automatic timeout occured");
}

通过使用新的@Schedule 注释,您可以广泛控制调用超时方法的时间和频率。最大的好处:您不再需要“从外面”启动计时器。

甲骨文写道:

Automatic timers are created by the EJB container when an enterprise bean that contains methods annotated with the @Schedule or @Schedules annotations is deployed. An enterprise bean can have multiple automatic timeout methods, unlike a programmatic timer, which allows only one method annotated with the @Timeout annotation in the enterprise bean class.

关于java - 如何在部署时启动 EJB 计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1265914/

相关文章:

java - 如何在不重新启动整个 JBoss 服务器的情况下更新我的 .jsp 文件?

jboss - 在 wildfly 8.2 中的 standalone-full.xml 中设置系统属性

java - 如何在 linux 中为 java 安装

java - Powermockito : argument matching for HashMap

Java字符串标记化: Split on pattern and retain pattern

java - 如何在 sessionCreated 方法中检索用户输入的数据

mysql - 尝试使用 EntityManager 创建 NativeQuery 时出现 IllegalStateException

java - 如何用JSP文件实现Post Redirect Get,数据保存在哪里?

java - 如何复制liferay portlet

java - 如何创建 EJB 3.2 Stateless Bean 项目并在 Wildfly 8 上运行它?