Python 3.7 – asyncio.sleep() and time.sleep()

You aren’t seeing anything special because there’s nothing much asynchronous work in your code. However, the main difference is that time.sleep(5) is blocking, and asyncio.sleep(5) is non-blocking. When time.sleep(5) is called, it will block the entire execution of the script and it will be put on hold, just frozen, doing nothing. But when you call … Read more

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

When to use and when not to use Python 3.5 `await` ?

By default all your code is synchronous. You can make it asynchronous defining functions with async def and “calling” these functions with await. A More correct question would be “When should I write asynchronous code instead of synchronous?”. Answer is “When you can benefit from it”. In cases when you work with I/O operations as … Read more