动态更改定时器中的超时时间间隔 [英] Dynamically change timeout interval in Timer
本文介绍了动态更改定时器中的超时时间间隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要制作如下的应用程序。
更改网络应用程序的输入值将会改变计时器的刷新间隔。
它需要动态,可以使用Timer吗?
I need to make an app as below. Changing a value in web app's input will change refresh interval in Timer. It needs to be dynamically, is it possible to do with Timer?
推荐答案
使用 TimerService 。在此示例中,任何先前的给定名称的计时器在启动新的定时器之前都会被取消,新的定时器将使用新的intervall
Use the TimerService in an ejb. In this example any previous timer with a given name is canceled before initiating the new timer with new intervall
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
@Stateless
public class TimerBean {
@Resource
protected TimerService timerService;
@Timeout
public void timeoutHandler(Timer timer) {
String name = timer.getInfo().toString();
System.out.println("Timer name=" + name);
}
public void startOrModifyTimer(long initialExpiration, long interval, String name){
//Cancel previous timer
Collection<Timer> timers = timerService.getAllTimers();
for (Timer timer: timers) {
if (timer.getInfo().equals(name)) {
timer.cancel();
}
}
TimerConfig config = new TimerConfig();
config.setInfo(name);
config.setPersistent(false);
timerService.createIntervalTimer(initialExpiration, interval, config);
}
}
这篇关于动态更改定时器中的超时时间间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文