有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我需要创建一个间隔计时器,设置为每周自动运行一次。我不希望它基于用户输入启动,但我希望它在应用程序部署到服务器时创建。我看到的每个例子都有另一个类启动计时器。我不想使用消息驱动的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");
    }


}

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


共 (3) 个答案

  1. # 1 楼答案

    我过去做计时器的方法是在web上创建一个上下文侦听器。xml来配置计时器

    这样你就可以确保它是从容器启动的,当应用被关闭时,它会干净地关闭

  2. # 3 楼答案

    如果你的项目可以使用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.