netty 4-2 定时任务

public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //比如这里我们有一个非常费时的操作。将其弄到NioEventLoop中的queue中就可以了
//        Thread.sleep(10*1000);
//        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端  这个是channelRead 方法", CharsetUtil.UTF_8));
ctx.channel().eventLoop().execute(()-> {//eventLoop这个是一个线程在执行,如果是多个任务,会把任务放在queue中
    try {
        Thread.sleep(10*1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端  这个是channelRead 方法", CharsetUtil.UTF_8));
});

        ctx.channel().eventLoop().execute(()-> {//eventLoop这个是一个线程在执行,如果是多个任务,会把任务放在queue中
            try {
                Thread.sleep(20*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端  这个是channelRead 方法2", CharsetUtil.UTF_8));
        });

        ctx.channel().eventLoop().schedule(()-> {//eventLoop这个是一个线程在执行,如果是多个任务,会把任务放在queue中
//            try {
                Thread.sleep(5*1000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端  这个是channelRead 方法2", CharsetUtil.UTF_8));
        },5, TimeUnit.SECONDS);

//        System.out.println("服务器端:Thread.currentThread().getName() = " + Thread.currentThread().getName());
//        //这个方法是干嘛的呢。有上下文对象,我们可以拿到很多东西,还有msg
//        System.out.println("ctx = " + ctx);
//        //就像我们之前用ByteBuffer 一样。我们需要将数据封装到缓冲对象
//        ByteBuf byteBuf = (ByteBuf) msg;//这个是netty封装后的buf 性能明显是比之前的高的。
//        System.out.println("byteBuf.toString(CharsetUtil.UTF_8) = " + byteBuf.toString(CharsetUtil.UTF_8));



    }

现在如果是定时任务,我们因为用了eventLoop所以,就一个线程,先要执行完成上面的任务之后,才会执行定时任务,所以等待时间是有可能被加长的。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值