Question

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).

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top