Netty工具类HashedWheelTimer
Netty工具类HashedWheelTimer
http://my.oschina.net/haogrgr/blog/489320
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); } }