为什么Netty不执行我的定时任务?
Why doesn't Netty execute my scheduled task?
使用 Java 8 和 Netty 4.1.1.Final,我希望下面的测试用例能够成功,但它超时了。有什么不懂的w.r.t。 nettys事件循环和任务调度?
public class SchedulerTest {
CountDownLatch latch;
TimerHandler handler;
static class TimerHandler extends ChannelInboundHandlerAdapter {
ChannelHandlerContext ctx;
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
this.ctx = ctx;
}
private void timeout(final long ms) {
ctx.executor().schedule(() -> {
ctx.fireUserEventTriggered(ms);
}, ms, TimeUnit.MILLISECONDS);
}
}
static class TimeoutReactor extends ChannelInboundHandlerAdapter {
CountDownLatch latch;
public TimeoutReactor(CountDownLatch latch) {
super();
this.latch = latch;
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
System.out.println("userEventTriggered");
latch.countDown();
super.userEventTriggered(ctx, evt);
}
}
@Before
public void setUp() throws Exception {
latch = new CountDownLatch(2);
handler = new TimerHandler();
TimeoutReactor reactor = new TimeoutReactor(latch);
new EmbeddedChannel(handler, reactor);
}
@Test(timeout = 1000)
public void test() throws InterruptedException {
handler.timeout(30);
handler.timeout(20);
latch.await();
}
}
这是因为 EmbeddedChannel 不是 "real" 通道实现,主要用于测试和嵌入式 ChannelHandler。您需要在给定的时间范围后调用 "runPendingTasks()" 才能获得它 运行。如果您使用 "real" 通道实现,它无需任何额外的方法调用即可工作。
使用 Java 8 和 Netty 4.1.1.Final,我希望下面的测试用例能够成功,但它超时了。有什么不懂的w.r.t。 nettys事件循环和任务调度?
public class SchedulerTest {
CountDownLatch latch;
TimerHandler handler;
static class TimerHandler extends ChannelInboundHandlerAdapter {
ChannelHandlerContext ctx;
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
this.ctx = ctx;
}
private void timeout(final long ms) {
ctx.executor().schedule(() -> {
ctx.fireUserEventTriggered(ms);
}, ms, TimeUnit.MILLISECONDS);
}
}
static class TimeoutReactor extends ChannelInboundHandlerAdapter {
CountDownLatch latch;
public TimeoutReactor(CountDownLatch latch) {
super();
this.latch = latch;
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
System.out.println("userEventTriggered");
latch.countDown();
super.userEventTriggered(ctx, evt);
}
}
@Before
public void setUp() throws Exception {
latch = new CountDownLatch(2);
handler = new TimerHandler();
TimeoutReactor reactor = new TimeoutReactor(latch);
new EmbeddedChannel(handler, reactor);
}
@Test(timeout = 1000)
public void test() throws InterruptedException {
handler.timeout(30);
handler.timeout(20);
latch.await();
}
}
这是因为 EmbeddedChannel 不是 "real" 通道实现,主要用于测试和嵌入式 ChannelHandler。您需要在给定的时间范围后调用 "runPendingTasks()" 才能获得它 运行。如果您使用 "real" 通道实现,它无需任何额外的方法调用即可工作。