英文:
Changing timer after startup in Java EE TimerService
问题
在这段代码中,我在启动时使用了一个 TimerService
来初始化一个每隔四秒运行一次的任务。如果我需要在启动后更改频率呢?
@Startup
@Singleton
public class ProgrammaticScheduler {
@Resource
TimerService timerService;
@PostConstruct
public void initialize() {
timerService.createTimer(0, 4000, "每四秒执行一次的定时器");
}
@Timeout
public void programmaticTimeout(Timer timer) {
System.out.println("定时器超时触发");
}
}
英文:
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");
}
}
答案1
得分: 2
以下是翻译好的代码部分:
自从使用Java EE以来已经有一段时间了,但我想唯一的选项是取消原始计时器并创建一个新的。所以在你的`ProgrammaticScheduler`中添加类似这样的内容:
private Timer timerToChange;
@PostConstruct
public void initialize() {
timerToChange = timerService.createTimer(0, 4000, "每四秒执行一次的计时器");
}
public void changeTimer(**NEW_PARAMS**) {
timerToChange.cancel();
timerToChange = timerService.createTimer(**NEW_PARAMS**);
}
英文:
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**);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论