2007年9月24日星期一

EJB3的Timer Service

代码:
package com.xued.timer;

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerService;

@Stateless
public class TimerBean implements TimerBeanLocal {

    @Resource
    private TimerService ts;

    public void cancelAllSchedule() {
        for (Object obj : ts.getTimers()) {
            Timer timer = (Timer) obj;
            timer.cancel();
        }
    }

    public void repeatSchedule() {
        long start = 5000;
        ts.createTimer(start, 9000, null);
        System.out.println("TimerBean: Timer created for first expire after " + start + "ms");
    }

    @Timeout
    public void handleTimeout(Timer timer) {
        System.out.println("TimerBean: handle timeout occured ");
    }
}

cancelAllSchedule()方法用于在设定Timer之前先取消所有关联到这个EJB的Timer,如果不这样做,则容器会将上次运行的Timer关联到这个EJB。利用这个特性,如果Timer的策略不会改变的话,则repeatSchedule()方法只需要在初次部署的时候调用一次就够了,下次重启动的时候,容器会记住你设置的策略,并自动应用到这个EJB上面。
@Timeout指定Timer到点的时候需要执行的方法。
另外,第一次部署TimerBean的时候需要调用repeatSchedule()方法来激活Timer,这就需要一个客户端,手工执行过于麻烦。在JBoss里可以写一个启动时自动执行的管理Bean,代码如下:

接口
package com.xued.timer;

import org.jboss.annotation.ejb.Management;

@Management
public interface TimerInitialService {

    void create() throws Exception;

    void start() throws Exception;

    void stop();

    void destroy();
   
}

实现类
package com.xued.timer;

import javax.ejb.EJB;
import org.jboss.annotation.ejb.Service;

@Service
public class TimerInitialServiceImpl implements TimerInitialService{

    @EJB
    TimerBeanLocal timerbean;
   
    public void create() throws Exception {
        System.out.println("TimerInitialService Started!");
        timerbean.cancelAllSchedule();
        timerbean.repeatSchedule();
    }

    public void start() throws Exception {
    }

    public void stop() {
    }

    public void destroy() {
    }

}

这样启动的时候,就会自动去调用
cancelAllSchedule()和repeatSchedule()两个方法,Timer就被激活了。

没有评论: