Skip to main content
Taught by Tech Leads

Master pipelines, cloud & AI to become an operational Data Engineer.

DataScientist.fr
Image de Python sleep function guide - Practical tutorial
Python

Python sleep function guide - Practical tutorial

Photo de Romain DE LA SOUCHÈRE

Tech Lead, CTO AXI Technologies

Published on 2 janvier 2025 · 10 min of reading

Have you ever thought about slowing down your Python code to optimize performance or simulate delays? While the main goal is often to speed up execution, there are situations that require a strategic pause. Whether to wait for a file download, synchronize API calls, or manage graphical user interfaces, using Python's sleep() function can be crucial. In this article, we will explore various ways to integrate pauses into your code, using time.sleep(), decorators, threads, Async IO, and GUI libraries like Tkinter and wxPython. Let's dive into this fascinating world together!
Have you ever needed to make your Python program wait for something? Most of the time, you want your code to run as quickly as possible. But there are times when letting your code sleep for a bit is actually in your best interest.
In this tutorial, you will learn to add Python calls
  • time.sleep()
  • Decorators
  • Threads
  • Async IO
  • Graphical interfaces
This article is aimed at intermediate developers looking to deepen their knowledge of Python. If that sounds like you, then let's get started!

Add a Python sleep() call with time.sleep()

Python provides built-in support to pause your program. The time module has a sleep() function that you can use to suspend the execution of the calling thread for the number of seconds you specify.
Here is an example of using time.sleep():
python
If you run this code in your console, you should notice a delay before you can enter a new command in the REPL.
You can test the duration of the pause using Python's timeit module:
python
Here, you run the timeit module with the -n parameter, which tells timeit how many times to execute the following statement. You can see that timeit executed the statement 3 times and that the best execution time was 3 seconds, which is what we expected.
The default number of times timeit will run your code is one million. If you were to run the code above with the default -n, then at 3 seconds per iteration, your terminal would be blocked for about 34 days! The timeit module has several other command-line options that you can check out in its documentation.
Let's create something a bit more realistic. A system administrator needs to know when one of their websites goes down. You want to be able to check the website's status code regularly, but you can't poll the web server constantly, or it will affect performance. One way to do this check is to use a Python sleep() call:
python
Here, you create uptime_bot(), which takes a URL as an argument. The function then tries to open that URL using urllib. If there is an HTTPError or URLError, then the program catches it and prints it. (In a real environment, you would log the error and probably send an email to the webmaster or system administrator.)
If no error occurs, then your code prints that everything is fine. Regardless, your program will sleep for 60 seconds. This means you access the website only once per minute. The URL used in this example is bad, so it will display the following in your console once a minute.
Go ahead and update the code to use a valid URL, like http://www.google.com. Then you can re-run it to see it work successfully. You could also try updating the code to send an email or log the errors. For more information on how to do this, check out sending emails with Python and logging in Python.

Add a Python sleep() call with decorators

There are times when you need to retry a function that has failed. A popular use case for this is when you need to retry downloading a file because the server was busy. You generally don't want to make a request to the server too often, so adding a Python sleep() call between each request is desirable.
Another use case I have personally experienced is when I need to check the status of a user interface during an automated test. The user interface may load faster or slower than usual, depending on the computer I'm testing on. This can change what is displayed on the screen at the time my program checks something.
In this case, I can tell the program to sleep for a moment and then recheck things a second or two later. This can make the difference between a successful test and a failed test.
You can use a decorator to add a Python sleep() call in one of these cases. If you're not familiar with decorators, or if you want to refresh your memory about them, check out the introduction to Python decorators. Let's see an example:
python
sleep() is your decorator. It accepts a timeout value and the number of times it should retry, which defaults to 3. Inside sleep() is another function, the_real_decorator(), which accepts the decorated function.
Finally, the innermost function, wrapper(), accepts the arguments and keywords you pass to the decorated function. This is where the magic happens! You use a while loop to retry calling the function. If there is an exception, then you call time.sleep(), increment the retries counter, and attempt to relaunch the function.
Now, rewrite uptime_bot() to use your new decorator:
Here, you decorate uptime_bot() with a sleep() of 3 seconds. You have also removed the original while loop, as well as the old call to sleep(60). The decorator now handles that.
Another change you made is adding a raise inside the exception handling blocks. This is to ensure the decorator works correctly. You could write the decorator to handle these errors, but since these exceptions only apply to urllib, it might be better to keep the decorator as is. This way, it will work with a wider variety of functions.
There are a few improvements you could make to your decorator. If it runs out of attempts and still fails, then you could make it re-raise the last error. The decorator will also wait 3 seconds after the last failure, which might be something you don't want to happen. Feel free to try this as an exercise!

Add a Python sleep() call with threads

There are also times when you might want to add a Python sleep() call to a thread. Perhaps you are running a migration script against a database with millions of records in production. You don't want to cause downtime, but you also don't want to wait longer than necessary to finish the migration, so you decide to use threads.
To prevent clients from noticing any slowdown, each thread should run for a short period and then sleep. There are two ways to do this:
  1. Use time.sleep() as before.
  2. Use Event.wait() from the threading module.
Let's start by looking at time.sleep().

Using time.sleep()

The logging cookbook of Python shows an interesting example that uses time.sleep(). The logging module in Python is thread-safe, so it is a bit more useful than just print statements for this exercise. The following code is based on that example:
python
Here, you use Python's threading module to create two threads. You also create a logging object that will log the threadName to stdout. Then, you start both threads and initiate a loop to log from the main thread periodically. You use KeyboardInterrupt to catch the user pressing Ctrl+C.
Try running the code above in your terminal. You should see output similar to the following:
As each thread runs and then sleeps, the logging output is printed to the console. Now that you've tried an example, you should be able to use these concepts in your own code.

Using Event.wait()

The threading module provides an Event() that you can use like time.sleep(). However, Event() has the added advantage of being more responsive. The reason for this is that when the event is set, the program will exit the loop immediately. With time.sleep(), your code will have to wait for the Python sleep() call to finish before the thread can exit.
The reason you would want to use wait() here is that wait() is non-blocking, while time.sleep() is blocking. This means that when you use time.sleep(), you will block the main thread from continuing to execute while it waits for the sleep() call to finish. wait() solves this problem. You can learn more about how all this works in the Python threading documentation.
Here is how you add a Python sleep() call with Event.wait():
python
In this example, you create threading.Event() and pass it to worker(). (Remember that in the previous example, you passed a dictionary instead.) Then, you set up your loops to check if the event is set or not. If it is not, then your code prints a message and waits a bit before checking again. To set the event, you can press Ctrl+C. Once the event is set, worker() will return and the loop will break, ending the program.
Take a closer look at the code block above. How would you pass a different sleep time to each worker thread? Can you figure it out? Feel free to tackle this exercise on your own!

Add a Python sleep() call with Async IO

Asynchronous capabilities were added to Python in version 3.4, and this feature set has aggressively evolved since then. Asynchronous programming is a type of parallel programming that allows you to run multiple tasks at the same time. When one task finishes, it will notify the main thread.
asyncio is a module that allows you to add a Python sleep() call asynchronously. If you are not familiar with implementing asynchronous programming in Python, check out Async IO in Python: A Complete Guide and Concurrency and Parallel Programming in Python.
Here is an example from the Python documentation:
python
In this example, you run main() and make it sleep for one second between two print() calls.
Here is a more compelling example from the Coroutines and Tasks section of the asyncio documentation:
python
In this code, you create a worker called output() that takes the number of seconds to sleep and the text to print. Then, you use Python's await keyword to wait for the output() code to execute. await is required here because output() has been marked as an async function, so you cannot call it like you would a normal function.
When you run this code, your program will execute await 3 times. The code will wait 1, 2, and 3 seconds, for a total wait time of 6 seconds. You can also rewrite the code to have the tasks run in parallel:
python
Now, you use the concept of tasks, which you can create with create_task(). When you use tasks in asyncio, Python will run the tasks asynchronously. So when you run the code above, it should finish in 3 seconds total instead of 6.

Conclusion

With this tutorial, you have acquired a valuable new technique to add to your Python toolbox! You know how to add delays to pace your applications and prevent them from using too many system resources. You can even use Python sleep() calls to help your GUI code redraw more efficiently. This will enhance the user experience for your clients!
To recap, you have learned to add Python sleep() calls with the following tools:
  • time.sleep()
  • Decorators
  • Threads
  • asyncio
Now you can take what you have learned and start making your code sleep!

Want to go further?

This topic is part of our Become a Data Analyst course. Browse the full programme, or get it by email.

Share with

Photo de Romain DE LA SOUCHÈRE

Romain DE LA SOUCHÈRE

Tech Lead, CTO AXI Technologies

Expert Data Engineering et Cloud, Romain affiche plus de 11 ans d'expérience, dont plusieurs années comme Lead Developer sur des solutions Smart Building haute performance. Il y a conçu et mis en production des moteurs de traitement capables d'absorber des centaines de milliers de données de capteurs par minute, ainsi que des bases clusterisées gérant plus de 10 millions de données dynamiques. Certifié Microsoft Azure DevOps Engineer Expert, il maîtrise aussi bien le développement back-end (Python, C#) que le DevOps (Docker, Kubernetes, Terraform) et les agents LLM. Formateur en Python, cloud, DevOps et IA générative appliquée, il forme avec une obsession : Amener chaque apprenant à concevoir et déployer des architectures réellement scalables en production.

» Learn More

Associated trainings

All our trainings
Image de la formation Become a Data Analyst
Become a Data Analyst
6 months
Intermediate
Guarantee
Image de la formation Become a Data Engineer
Become a Data Engineer
9 months
Advanced
Guarantee