Lets consider the situation:
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()开发者_StackOverflow;
Thread.sleep(sleepDelay);
establishTimeout();
}
What is happening on the timeline:
0 : establishTimeout(), cancelTimeout()
sleepDelay : establishTimeout()
delay : timerTask.run()
Why timerTask runs not at the sleepDelay + delay
?
How to make it work as expected?
Because delay
is interpreted as seconds and sleepDelay
is interpreted as milliseconds. Use sleepDelay * 1000
to get the result you want.
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);
}
}
精彩评论