1

In this code I use a TimerService on startup to initiate a task that will run every four seconds. What if I need to change the frequency after startup?

@Startup
@Singleton
public class ProgrammaticScheduler {
 
    @Resource
    TimerService timerService;
 
    @PostConstruct
    public void initialize() {
        timerService.createTimer(0, 4000, "Every four seconds timer");
    }
 
    @Timeout
    public void programmaticTimeout(Timer timer) {
        System.out.println("timeout triggered");
    }
}
ps0604
  • 1,227
  • 23
  • 133
  • 330

1 Answers1

2

It's been a while since with Java EE but I guess the only option is to cancel the original timer and create a new. So adding something like this in your ProgrammaticScheduler:

private Timer timerToChange;

@PostConstruct
public void initialize() {
    timerToChange = timerService.createTimer(0, 4000, "Every four seconds timer");
}

public void changeTimer(**NEW_PARAMS**) {
    timerToChange.cancel();
    timerToChange = timerService.createTimer(**NEW_PARAMS**);
}
Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
pirho
  • 11,565
  • 12
  • 43
  • 70