java - 为什么Netty不执行我的定时任务?

标签 java netty scheduler

使用 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 不是“真正的”Channel 实现,主要可用于测试和嵌入式 ChannelHandler。您需要在给定时间范围后调用“runPendingTasks()”才能运行它。如果您使用“真正的” Channel 实现,它将无需任何额外的方法调用即可工作。

关于java - 为什么Netty不执行我的定时任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38412579/

相关文章:

playframework - 如何更改 Play2 正在监听的 HTTP 端口

c - 在免费 RTos 中实现调度程序

java - 在netbeans 6.8中将java应用程序连接到mysql服务器

websocket - Netty:正确关闭WebSocket

java - 将 Activity 转换为使用 Database 和 Adapter 类的 Fragment

netty重用 channel

python - 未应用于 setuid ed 进程的用户的 Linux 组调度

c++ - SCHED_RR 线程上的 Posix 计时器正在使用 100% CPU

java - Java 字节码中存在多个静态 block 会发生什么情况?

java - 我应该使用什么 java 库来进行图像裁剪/信箱处理?