2011-02-07 37 views
1

觸發讓我們考慮的情況:Netty HashedWheelTimer意外的行爲。超時事先

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

因爲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); 
    } 
} 
+0

問題中的代碼是抽象的,因此行:「Thread.sleep(sleepDelay);」只是代表了實際代碼中的一些延遲。可以肯定的是,`delay`和`sleepDelay`是成比例的;) – 2011-02-15 07:39:48