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:






原文地址:https://www.cnblogs.com/strinkbug/p/5179345.html