Python Glossary Русский

Python 3.4+Async programmingterm

asyncio.TimerHandle

event loop

The Handle of a delayed callback, returned by loop.call_later() and loop.call_at(). Its when() method tells when the call is scheduled in loop time.

Syntax

handle = loop.call_later(delay, callback, *args)  # handle.when(), handle.cancel()

when() returns neither seconds until the call nor wall-clock time but a loop.time() value — the loop's monotonic clock whose zero means nothing; the delay is handle.when() - loop.time(). Cancel timers you no longer need: otherwise the callback fires even after the coroutine that wanted it has moved on. To wait and continue inside a coroutine you need no timers at all — just await asyncio.sleep().

Examples

import asyncio
async def main():
    loop = asyncio.get_running_loop()
    h = loop.call_later(10, print, 'не дождёмся')
    print(type(h).__name__)  # → TimerHandle
    print(round(h.when() - loop.time()))  # → 10 — секунд до вызова
    h.cancel()
    print(h.cancelled())  # → True
    await asyncio.sleep(0.01)
asyncio.run(main())

See also

Open in the full glossarydocs.python.orgReport an inaccuracy