Sling Academy
Home/Python/Python asyncio.sleep() function (with examples)

Python asyncio.sleep() function (with examples)

Last updated: July 26, 2023

This concise, practical article is about the asyncio.sleep() function in modern Python.

The Fundamentals

The asyncio.sleep() function is a coroutine that suspends the execution of a task or coroutine for a given number of seconds. It is part of the asyncio module, which provides a framework for writing asynchronous code in Python. The asyncio module was added to Python in version 3.4 as a provisional package, and it became stable in version 3.5.

Syntax:

asyncio.sleep(delay, result=None)

Parameters explained:

  • delay: a number of seconds to wait before resuming the coroutine. It must be a positive or zero float or integer.
  • result: an optional value to return to the caller when the coroutine completes. It can be any Python object.

The function returns the same value as the result parameter, or None if not provided.

The asyncio.sleep() function can be seen in the vast majority of online tutorials and articles related to Python concurrency (you’ll also see it a lot on Sling Academy as well). In real-world applications, the asyncio.sleep() function has many uses, especially to create tasks that run periodically at a fixed interval.

At this point, you might get bored with words and concepts. It’s time to get your hands dirty with some code examples.

Examples

The Most Basic Example

The simplest way to use asyncio.sleep() is to create a coroutine that sleeps for a given number of seconds and then prints a message. The code below creates a coroutine that sleeps for 3 seconds and then prints “Welcome to Sling Academy!”:

# This example uses Python 3.11.4

import asyncio

async def hello():
    await asyncio.sleep(3)
    print("Welcome to Sling Academy!")

asyncio.run(hello())

You’ll see the output after 3 seconds, without blocking the main thread:

Welcome to Sling Academy!

Intermediate Example

A more interesting way to use asyncio.sleep() is to create multiple coroutines that sleep for different amounts of time and then print their names. In this example, we’ll create three coroutines that sleep for 1, 2, and 3 seconds, respectively, and then print “Hello One”, “Hello Two”, and “Hello Three” (you can choose other cool names if you want):

# This example uses Python 3.11.4

import asyncio

async def say_hello(name, delay):
    await asyncio.sleep(delay)
    print(f"Hello {name}")

async def main():
    await asyncio.gather(
        say_hello("One", 1),
        say_hello("Two", 2),
        say_hello("Three", 3),
    )

asyncio.run(main())

You will see the following greetings appear in turn:

Hello One
Hello Two
Hello Three

Advanced Example

A more complex way to use asyncio.sleep() is to create a periodic task that runs a coroutine every n seconds. For example, this code creates a periodic task that prints the current time every 2 seconds (but no more than 10 times):

# slingacademy.com
# This example uses Python 3.11.4

import asyncio
import datetime


async def print_time():
    print(datetime.datetime.now())
    await asyncio.sleep(2)


async def main():
    total_runs = 10
    current_run = 0

    while current_run < total_runs:
        await print_time()
        current_run += 1


asyncio.run(main())

Output:

2023-07-26 13:35:42.208372
2023-07-26 13:35:44.209667
2023-07-26 13:35:46.211123
2023-07-26 13:35:48.211765
2023-07-26 13:35:50.213030
2023-07-26 13:35:52.213790
2023-07-26 13:35:54.214435
2023-07-26 13:35:56.215158
2023-07-26 13:35:58.216296
2023-07-26 13:36:00.217480

Afterword

You’ve learned about the asyncio.sleep() function and walked through some examples of using it in practice. As of now, you can take advantage of it to write more efficient asynchronous code in modern Python projects. If you have any questions, just leave a comment. This tutorial ends here. Happy coding & enjoy your day!

Next Article: Python async/await and timeouts (with examples)

Previous Article: Python asyncio.run() function (with examples)

Series: Python Asynchronous Programming Tutorials

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots