Skip to content

Effortlessly Waiting in Python: A Complete Guide to Using the wait Method

[

Python sleep(): How to Add Time Delays to Your Code

by Mike Driscoll intermediate


Have you ever needed to make your Python program wait for something? Most of the time, you’d want your code to execute as quickly as possible. But there are times when letting your code sleep for a while is actually in your best interest.

For example, you might use a Python sleep() call to simulate a delay in your program. Perhaps you need to wait for a file to upload or download, or for a graphic to load or be drawn to the screen. You might even need to pause between calls to a web API, or between queries to a database. Adding Python sleep() calls to your program can help in each of these cases, and many more!

In this tutorial, you’ll learn how to add Python sleep() calls with:

  • time.sleep()
  • Decorators
  • Threads
  • Async IO
  • Graphical User Interfaces

This article is intended for intermediate developers who are looking to grow their knowledge of Python. If that sounds like you, then let’s get started!

Adding a Python sleep() Call With time.sleep()

Here’s an example of how to use time.sleep():

import time
time.sleep(3) # Sleep for 3 seconds

If you run this code in your console, you will experience a delay of 3 seconds before you can enter a new statement in the REPL.

You can test how long the sleep lasts by using Python’s timeit module:

Terminal window
$ python3 -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop

In the above example, the timeit module is used with the -n parameter to specify how many times to run the sleep statement. The output shows that the sleep lasted for 3 seconds, as expected.

It’s important to note that in Python 3.5 and later, the behavior of time.sleep() was changed. The sleep will last at least the number of seconds specified, even if it is interrupted by a signal. However, this does not apply if the signal itself raises an exception.

Now, let’s look at a more practical example. Suppose you are a system administrator who needs to be notified when one of your websites goes down. You want to regularly check the website’s status code, but you also want to add a delay between each check to avoid overwhelming the server. Here’s how you can use time.sleep() to accomplish this:

import requests
import time
def check_website_status(url):
while True:
try:
response = requests.get(url)
if response.status_code != 200:
print(f"Error: {response.status_code}")
else:
print("Website is up and running")
except requests.exceptions.RequestException as e:
print(e)
time.sleep(60) # Delay for 60 seconds before checking again
if __name__ == "__main__":
url = "https://www.example.com"
check_website_status(url)

In the code above, we defined a function check_website_status() that continuously sends HTTP requests to the specified URL and checks the response status code. If the status code is not 200 (OK), we print an error message. Otherwise, we print a success message indicating that the website is up and running.

The time.sleep(60) statement adds a delay of 60 seconds between each check. This ensures that we don’t overload the server with too many requests in a short period of time.

By adding a delay with time.sleep(), we can effectively check the status of a website at regular intervals without putting unnecessary strain on the server.



Recommended Video Course
Using sleep() to Code a Python Uptime Bot