Changing timer after startup in Java EE TimerService.

huangapple go评论57阅读模式
英文:

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**);
}

huangapple
  • 本文由 发表于 2020年7月22日 22:47:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/63037027.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定