When writing asynchronous Python code, you'll likely need to add delays or pauses in your logic. Python provides two ways to achieve this - asyncio.sleep() and time.sleep(). But these two methods have key differences that impact when you should use each.
Asyncio Sleep Allows Asynchronous Code to Pause
The
import asyncio
async def my_coro():
print('Pausing coroutine')
await asyncio.sleep(2)
print('Resumed coroutine')
asyncio.run(my_coro())
This allows other asynchronous tasks to run while
Time Sleep Blocks the Whole Thread
Meanwhile,
import time
def my_func():
print('Pausing function')
time.sleep(2)
print('Resumed function')
my_func()
So
Key Takeaways
The choice comes down to whether you want an asynchronous or blocking pause in your Python code flow.