Skip to content

Effortlessly Waiting in Python: A Tutorial

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()

Python has built-in support for putting your program to sleep. The time module has a function sleep() that you can use to suspend execution of the calling thread for however many seconds you specify.

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, then you should experience a delay before you can enter a new statement in the REPL.

Note: In Python 3.5, the core developers changed the behavior of time.sleep() slightly. The new Python sleep() system call will last at least the number of seconds you’ve specified, even if the sleep is interrupted by a signal. This does not apply if the signal itself raises an exception, however.

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

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

Here, you run the timeit module with the -n parameter, which tells timeit how many times to run the statement that follows. You can see that timeit ran the statement 3 times and that the best run time was 3 seconds, which is what was expected.

The default number of times that timeit will run your code is one million. If you were to run the above code with the default -n, then at 3 seconds per iteration, your terminal would hang for approximately 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 don’t want to bombard the server with requests. Instead, you want to check the website’s status code every 10 seconds. Here’s a simple Python program that accomplishes this:

import requests
import time
def check_website(url):
while True:
response = requests.get(url)
if response.status_code == 200:
print(f"Website is up with status code {response.status_code}")
print(f"Website is down with status code {response.status_code}")

In this code, we create a function check_website() that accepts a URL. Inside the function, we use a while loop to keep making requests to the website every 10 seconds. If the response status code is 200, we print a message saying the website is up. Otherwise, we print a message saying the website is down.

With this code, you can easily monitor the status of any website without bombarding the server with continuous requests. The time.sleep(10) call ensures that we wait for 10 seconds between each request.

In this tutorial, you learned how to add time delays to your Python code using the sleep() function from the time module. This can be useful in simulating delays, creating pauses between operations, or controlling the flow of your program. Sleep well, and happy coding!

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

Note: The content of this article is for educational purposes only. The Python code provided is a simplified example and may not work in all scenarios without proper error handling and adjustments.