Async IO Sleep vs Time Sleep in Python - When to Use Each

Mar 17, 2024 ยท 2 min read

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 asyncio.sleep() function is designed to work with Python's asyncio module for asynchronous programming. Using it will pause the coroutine where it is called, allowing other coroutines in the event loop thread to execute during the pause.

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 my_coro is paused. This is essential for writing efficient async code.

Time Sleep Blocks the Whole Thread

Meanwhile, time.sleep() blocks the whole thread it is called from. Other code in that thread cannot run during the pause:

import time

def my_func():
    print('Pausing function')
    time.sleep(2)
    print('Resumed function')

my_func() 

So time.sleep() is not asynchronous - it blocks all other processing.

Key Takeaways

  • Use asyncio.sleep() for asynchronous coroutines when you want delays without blocking.
  • Use time.sleep() when you specifically want to pause all processing in the current thread.
  • Don't use time.sleep() in asyncio coroutines as it will block the event loop thread.
  • The choice comes down to whether you want an asynchronous or blocking pause in your Python code flow.

    Browse by tags:

    Browse by language:

    The easiest way to do Web Scraping

    Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


    Try ProxiesAPI for free

    curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

    <!doctype html>
    <html>
    <head>
        <title>Example Domain</title>
        <meta charset="utf-8" />
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
    ...

    X

    Don't leave just yet!

    Enter your email below to claim your free API key: