在 ejb 定时器中,与 Start&Stop 相关的最接近的想法是 Create&Cancel。
发布的代码显示您正在使用Automatic 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
,这意味着需要更多的代码,但您可以决定何时创建特定的计时器。
//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...");
}
取消操作与自动定时器相同。