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/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值