netty HashedWheelTimer简单实例

netty定时器HashedWheelTimer
netty中的Timer管理,使用了的Hashed time Wheel的模式,Time Wheel翻译为时间轮,是用于实现定时器timer的经典算法。算法的核心是将时间划分结合,可能在时间准确性上会比一般的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);
    }
}
原文  http://www.tianjiaguo.com/tech/netty定时器hashedwheeltimer/

猜你喜欢

转载自liyuanchao2004.iteye.com/blog/2023152