Netty HashedWheelTimer意外行为。超时会事先触发

时间:2011-02-07 10:18:04

标签: java timer timeout

让我们考虑一下情况:

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运行? 如何让它按预期工作?

1 个答案:

答案 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);
    }
}