gpt4 book ai didi

java - 重启定时器失败

转载 作者:行者123 更新时间:2023-12-01 15:04:39 25 4
gpt4 key购买 nike

我想在收到 KeepAlive 时重新启动计时器,问题是有时它不会重新启动,而是创建一个新计时器,因此,最终计时器达到了限制:

public class KeepAliveTimer {


long macAddress;
Timer timer;
String ip;


public KeepAliveTimer(long mac, String ipAddress){
this.macAddress = mac;
this.ip = ipAddress;

timer = new Timer();

TimerTask timerTask = new TimerTask() {

@Override
public void run() {

timerFinished();

}
};

timer.schedule(timerTask, 10*60*1000);
}


public void update() {


TimerTask timerTask = new TimerTask() {

@Override
public void run() {
timerFinished();

}
};
timer.cancel();
timer.purge();
timer = new Timer();
timer.schedule(timerTask, 10*60*1000);
}

public void timerFinished() {

//tasks
}

}

对象 KeepAliveTimer 在收到第一个 keepAlive 时创建,并由后续的 keepAlive 更新

最佳答案

您不应该取消整个计时器,而只能取消TimerTask。这就是我编写代码的方式:

public class KeepAliveTimer {
final Timer timer = new Timer();
final long macAddress;
final String ip;
volatile TimerTask timerTask;

public KeepAliveTimer(long mac, String ipAddress) {
this.macAddress = mac;
this.ip = ipAddress;
}
public void update() {
if (timerTask != null) timerTask.cancel();
timer.schedule(timerTask(), 10 * 60 * 1000);
}
private TimerTask timerTask() {
return timerTask = new TimerTask() {
@Override public void run() { timerFinished(); }
};
}
public void timerFinished() {
// tasks
}
}

请注意,我不会在构造函数内重复调度。您应该初始化

new KeepAliveTimer(mac, ip).update();

关于java - 重启定时器失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13139042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com