问题
I'm trying to use a simple automatic EJB schedule/timer. My code goes something like this:
@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() {
...
}
}
Is there a way to stop and restart automatic timers during the runtime? Please notice that I don't need to change the timeouts, I only need to stop and start the timers. All tutorials and examples I've found so far don't mention the stop/start concept at all (that is for the simple @Schedule timers).
回答1:
In ejb Timers the closer ideas related to Start&Stop are Create&Cancel.
The posted code shows that you are using Automatic Timer
which are very easy to create but, have a drawback: the Timer will be created automatically by Container only at deploy time.
This leave you a small margin for Create operations.
However, once created, a Timer can be canceled calling the Timer.cancel() method.
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();
}
}
}
And alternative is to create a Programatic Timer
, this implies a little more code, but you can decide when create a particular 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...");
}
The Cancel operation remains the same as Automatic Timer.
来源:https://stackoverflow.com/questions/21343367/is-there-a-way-to-stop-re-start-ejb-3-1-automatic-timer-during-runtime