让我们考虑一下情况:
import org.jboss.netty.util.HashedWheelTimer;
import org.jboss.netty.util.Timer;
import org.jboss.netty.util.Timeout;
import org.jboss.netty.util.TimerTask;
Timer timer = new HashedWheelTimer();
Timeout timeout = null;
void establishTimeout() {
timeout = timer.newTimeout(timerTask, delay, TimeUnit.SECONDS);
}
void cancelTimeout() {
timeout.cancel()
timeout = null;
}
public static void main(String[] args) {
establishTimeout();
cancelTimeout();
Thread.sleep(sleepDelay);
establishTimeout();
}
时间表上发生了什么:
0 : establishTimeout(), cancelTimeout()
sleepDelay : establishTimeout()
delay : timerTask.run()
为什么timerTask不在sleepDelay + delay
运行?
如何让它按预期工作?
答案 0 :(得分:0)
因为delay
被解释为秒,sleepDelay
被解释为毫秒。使用sleepDelay * 1000
获得所需的结果。
public class TaskTester {
static Timer timer = new HashedWheelTimer();
static Timeout timeout = null;
static int delay = 3;
static int sleepDelay = 2;
static TimerTask timerTask = new TimerTask(){
public void run(Timeout timeout) throws Exception {
System.out.printf("RUN %.3f%n", System.currentTimeMillis() / 1000.0);
}
};
static void establishTimeout() {
timeout = timer.newTimeout(timerTask, delay, TimeUnit.SECONDS);
}
static void cancelTimeout() {
timeout.cancel();
timeout = null;
}
public static void main(String[] args) throws InterruptedException {
System.out.printf("START %.3f%n", System.currentTimeMillis() / 1000.0);
establishTimeout();
cancelTimeout();
Thread.sleep(sleepDelay * 1000);
establishTimeout();
System.out.printf("MAIN DONE %.3f%n", System.currentTimeMillis() / 1000.0);
}
}