How can I add a connection timeout with asyncio? How can I add a connection timeout with asyncio? python-3.x python-3.x

How can I add a connection timeout with asyncio?


You can wrap the call to open_connection in asyncio.wait_for, which allows you to specify a timeout:

    with suppress(ssl.CertificateError):        fut = asyncio.open_connection(host[1], 443, ssl=True)        try:            # Wait for 3 seconds, then raise TimeoutError            reader, writer = yield from asyncio.wait_for(fut, timeout=3)        except asyncio.TimeoutError:            print("Timeout, skipping {}".format(host[1]))            continue

Note that when TimeoutError is raised, the open_connection coroutine is also cancelled. If you don't want it to be cancelled (though I think you do want it to be cancelled in this case), you have wrap the call in asyncio.shield.