AdamSkywalker AdamSkywalker - 1 year ago 102
HTTP Question

How to schedule HttpRequest in Netty channel?

I need to make several requests using one connection (http keep-alive) and I'd like to add delay between them. Right now in my last handler I write next HttpRequest in channel after LastHttpContent from previous request is received:

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
...
if (msg instanceof LastHttpContent) {
...
ctx.channel().writeAndFlush(nextHttpRequest);
...
}
}


I suppose that using
Thread.sleep
will block the whole netty reactor so I'm looking for a correct way to delay write in channel.

Answer Source

You can schedule a task to write the message using the ChannelContext's executor:

public class ScheduledHttpWriter extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if (msg instanceof LastHttpContent) {
            ctx.executor().schedule(new Runnable(){
                @Override
                public void run() {
                    ctx.channel().writeAndFlush(outBoundMessage);
                }
            }, 1000, TimeUnit.MILLISECONDS);
        }               
    }

}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download