netty定時器HashedWheelTimer(zz)


http://www.tianjiaguo.com/programming-language/java-language/netty%E5%AE%9A%E6%97%B6%E5%99%A8hashedwheeltimer/ 

netty中的Timer管理,使用了的Hashed time Wheel的模式,Time Wheel翻譯為時間輪,是用於實現定時器timer的經典算法。

我們看看netty的HashedWheelTimer的一個測試的例子,先new一個HashedWheelTimer,然后調用它的newTimeout方法,這個方法的聲明是這樣的:


    
/**
     * Schedules the specified {@link TimerTask} for one-time execution after
     * the specified delay.
     *
     * @return a handle which is associated with the specified task
     *
     * @throws IllegalStateException if this timer has been
     *                               {@linkplain #stop() stopped} already
     */

    
Timeout newTimeout(TimerTask task, long delay, TimeUnit unit);

這個方法需要一個TimerTask對象以知道當時間到時要執行什么邏輯,然后需要delay時間數值和TimeUnit時間的單位,像下面的例子中,我們在timer到期后會打印字符串,第一個任務是5秒后開始執行,第二個10秒后開始執行。


import org.jboss.netty.util.HashedWheelTimer;
import org.jboss.netty.util.Timeout;
import org.jboss.netty.util.Timer;
import org.jboss.netty.util.TimerTask;


import java.util.concurrent.TimeUnit;

/**
 * 12-6-6 下午2:46
 *
 * @author jiaguotian Copyright 2012 Sohu.com Inc. All Rights Reserved.
 */

public class TimeOutTest {
    
public static void main(String[] argv) {
        
final Timer timer = new HashedWheelTimer();
        timer
.newTimeout(new TimerTask() {
            
public void run(Timeout timeout) throws Exception {
                
System.out.println("timeout 5");
            
}
        
}, 5, TimeUnit.SECONDS);
        timer
.newTimeout(new TimerTask() {
            
public void run(Timeout timeout) throws Exception {
                
System.out.println("timeout 10");
            
}
        
}, 10, TimeUnit.SECONDS);
    
}
}

參考資料:
1:http://blog.hummingbird-one.com/?p=10048
2:







免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM