Skip to content
Search

Async-timeout

lastmod 2021-08-16created 2021-08-161 edits

Easy timeouts when using asyncio.

How to use

Timeout duration:

async with timeout(1.5):
    await inner()

Exact end time:

loop = asyncio.get_event_loop()
now = loop.time()

async with timeout_at(now + 1.5):
    await inner()

Check whether it timed out:

async with timeout(1.5) as cm:
    await inner()
print(cm.expired)

Returns True if execution of inner() was cancelled by the Timeout context manager.

If the inner() call explicitly raises TimeoutError, cm.expired is False.

The scheduled deadline is available as the .deadline attribute.

Check the scheduled end time:

async with timeout(1.5) as cm:
    cm.deadline

Reschedule the end:

async with timeout(1.5) as cm:
    cm.shift_by(1)  # add another second on waiting
    cm.shift_to(loop.time() + 5)  # reschedule to now+5 seconds

See also

Favorite site

author Zer0 sitemap