How can I periodically execute a function with asyncio?

For Python versions below 3.5: import asyncio @asyncio.coroutine def periodic(): while True: print(‘periodic’) yield from asyncio.sleep(1) def stop(): task.cancel() loop = asyncio.get_event_loop() loop.call_later(5, stop) task = loop.create_task(periodic()) try: loop.run_until_complete(task) except asyncio.CancelledError: pass For Python 3.5 and above: import asyncio async def periodic(): while True: print(‘periodic’) await asyncio.sleep(1) def stop(): task.cancel() loop = asyncio.get_event_loop() loop.call_later(5, stop) … Read more

How to limit concurrency with Python asyncio?

If I’m not mistaken you’re searching for asyncio.Semaphore. Example of usage: import asyncio from random import randint async def download(code): wait_time = randint(1, 3) print(‘downloading {} will take {} second(s)’.format(code, wait_time)) await asyncio.sleep(wait_time) # I/O, context will switch to main function print(‘downloaded {}’.format(code)) sem = asyncio.Semaphore(3) async def safe_download(i): async with sem: # semaphore limits … Read more

“Fire and forget” python async/await

Upd: Replace asyncio.ensure_future with asyncio.create_task everywhere if you’re using Python >= 3.7 It’s a newer, nicer way to spawn tasks. asyncio.Task to “fire and forget” According to python docs for asyncio.Task it is possible to start some coroutine to execute “in the background”. The task created by asyncio.ensure_future won’t block the execution (therefore the function … Read more