时间轮类
public class NettyTimer {
private final HashedWheelTimer timer;
public NettyTimer(int tickDuration, int ticksPerWheel) {
timer = new HashedWheelTimer(r -> new Thread(r,"HashedWheelTimer " + r.hashCode()),
tickDuration, TimeUnit.MILLISECONDS, ticksPerWheel);
}
public void addTask(TimerTask task, long delay, TimeUnit unit) {
timer.newTimeout(task, delay, unit);
}
public void addTimerTask(TimerTask task, long duration, TimeUnit unit) {
timer.newTimeout((timeout) -> {
task.run(timeout);
addTimerTask(task, duration, unit);
}, duration, unit);
}
public void stop() {
timer.stop();
}
}
测试
class NettyTimerTest {
@Test
void addTask() throws InterruptedException {
NettyTimer nettyTimer = new NettyTimer(1, 7);
nettyTimer.addTimerTask((timeout) -> System.out.println("Hello World!"), 1, TimeUnit.SECONDS);
Thread.currentThread().join();
}
@Test
void stop() {
}
}
依赖
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>5.0.0.Alpha2</version>
</dependency>