有没有办法在运行时停止/重新启动ejb 3.1自动定时器?

时间:2014-01-24 22:06:32

标签: ejb restart schedule

我正在尝试使用简单的自动EJB计划/计时器。我的代码是这样的:

@Singleton
@Lock(LockType.READ)
public class Scheduler {

    @Schedule(second = "0", minute = "*/20", hour = "*"),
    private void fetchSomeData() {
        ...
    }

    @Schedule(second = "0", minute = "*/5", hour = "*"),
    private void cleanThingsUp() {
        ...
    }

}

有没有办法在运行时停止并重启自动定时器?请注意,我不需要更改超时,我只需要停止并启动计时器。到目前为止我找到的所有教程和示例都没有提到停止/启动概念(即简单的 @Schedule 计时器)。

1 个答案:

答案 0 :(得分:3)

在ejb Timers中,与Start& Stop相关的更接近的想法是创建和取消。

发布的代码显示您使用的Automatic Timer非常容易创建,但有一个缺点:Timer仅在部署时由Container自动创建。 这为Create操作留下了一小部分余地。

但是,一旦创建,就可以取消Timer,调用Timer.cancel()方法。

e.g:

@Singleton
@Remote
public class MyTimer implements MyTimerRemote {

@Resource
TimerService timerService;

//MyTimer1, notice the info attribute
@Schedule (hour="*", minute="*", second="*", info="MyTimer1")
public void doSomthing(){
    System.out.println("Executing Timer 1");
}

//MyTimer2
@Schedule (hour="*", minute="*", second="*", info="MyTimer2")
public void doSomthing2(){
    System.out.println("Executing Timer 2");
}


//call this remote method with the Timer info that has to be canceled
@Override
public void cancelTimer(String timerInfo) {

    for (Timer timer: timerService.getTimers()) {
        if (timerInfo.equals(timer.getInfo())) {
            System.out.println("Canceling Timer: info: " + timer.getInfo());
            timer.cancel();
        }

    }   
}

另一种方法是创建一个Programatic Timer,这意味着更多的代码,但你可以决定何时创建一个特定的Timer。

//you can call this remote method any time 
@Override
public void createProgramaticTimer(String timerInfo) {
    System.out.println("Creating new PT: " + timerInfo);
    TimerConfig timerConf = new TimerConfig();
    timerConf.setInfo(timerInfo);
            //create a new programatic timer
    timerService.createIntervalTimer(1, 1000, timerConf); //just an example


}

@Timeout
public void executeMyTimer(Timer timer){
    System.out.println("My PT is executing...");

}

取消操作与自动定时器保持一致。