Skip to content

Easily Understand the Python Wait Command

[

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

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:

Terminal window
$ 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 overload the server with too many requests in a short period of time. Adding a delay between requests can help prevent this.

Here’s an example of how you might implement this using time.sleep():

import requests
import time
websites = ["http://www.example.com", "http://www.example.org", "http://www.example.net"]
for website in websites:
response = requests.get(website)
if response.status_code == 200:
print(f"{website} is up!")
else:
print(f"{website} is down!")
time.sleep(5) # Sleep for 5 seconds before making the next request

In this example, you import the requests library for making HTTP requests and the time module for using the sleep() function. You create a list of websites that you want to check, and then loop through each website.

You make a GET request to each website using requests.get(), and then check the response status code. If the status code is 200, then the website is considered “up,” and you print a corresponding message. If the status code is not 200, then the website is considered “down,” and you print a different message.

After each request, you add a time.sleep(5) call to pause the execution of the program for 5 seconds. This ensures that you don’t make too many requests too quickly and potentially overwhelm the server.

In this way, you can add a delay to your Python program using the time.sleep() function. This can be useful in various situations where you need to wait for something before proceeding further in your code.

In the next section, we’ll explore how to add a Python sleep() call using decorators.

Adding a Python sleep() Call With Decorators

Decorators are a powerful feature in Python that allow you to modify or enhance the behavior of functions or methods without changing their source code. You can also use decorators to add a sleep() call to a function or method to introduce a delay.

Here’s an example of how to create a decorator that adds a delay to a function:

import time
def delay(seconds):
def decorator(func):
def wrapper(*args, **kwargs):
time.sleep(seconds)
return func(*args, **kwargs)
return wrapper
return decorator
@delay(2) # Pause for 2 seconds
def greet(name):
print(f"Hello, {name}!")
greet("World")

In this example, you define a decorator function delay(seconds) that takes a number of seconds as an argument. Within the delay() function, you define another function, decorator(func), which will be used as the actual decorator.

Inside the decorator() function, you define yet another function, wrapper(*args, **kwargs), which is the replacement for the original function or method. In this wrapper function, you add a time.sleep(seconds) call to introduce a delay, and then call the original function or method using return func(*args, **kwargs).

After defining the decorator, you can use the @delay(2) syntax to apply it to a function. In this case, you apply the @delay(2) decorator to the greet() function, which means that any time you call greet(), it will include a 2-second delay.

When you run this code, you should see a 2-second delay before the “Hello, World!” message is printed to the console.

Decorators are a powerful tool in Python, and you can use them not only to add delays but also to modify or enhance the behavior of functions and methods in various ways.

In the next section, we’ll explore how to add a Python sleep() call using threads.

Adding a Python sleep() Call With Threads

Threads are a way to run multiple threads of execution within a single process. You can use threads to perform multiple tasks concurrently, such as making multiple network requests or performing computations in parallel.

In Python, you can use the threading module to work with threads, and you can add a sleep() call within a thread to introduce a delay.

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

import threading
import time
def worker():
print("Thread started")
time.sleep(3) # Sleep for 3 seconds
print("Thread finished")
threads = []
for _ in range(5):
thread = threading.Thread(target=worker)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()

In this example, you define a function worker() that will be executed within each thread. Inside the worker() function, you include a time.sleep(3) call to introduce a 3-second delay within each thread.

You create a list threads to store references to the thread objects, and then use a loop to create and start 5 threads. Each thread is created using threading.Thread() and targeted at the worker() function.

After starting all the threads, you use another loop to wait for each thread to finish using thread.join(). This ensures that the main thread waits for all the worker threads to complete before exiting.

When you run this code, you should see the message “Thread started” printed 5 times with a delay of 3 seconds between each message. After the delay, you should see the message “Thread finished” printed 5 times.

Using threads can be a powerful way to introduce parallelism into your Python programs, and adding a sleep() call within threads can help introduce delays as needed.

In the next section, we’ll explore how to add a Python sleep() call using async IO.

Adding a Python sleep() Call With Async IO

Async IO is a modern approach to concurrency in Python that allows you to write asynchronous code using the async and await keywords. You can use asyncio.sleep() to introduce a delay in an async IO program.

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

import asyncio
async def main():
print("Sleeping...")
await asyncio.sleep(3) # Sleep for 3 seconds
print("Done sleeping")
asyncio.run(main())

In this example, you define an async function main(), which is the entry point for the async IO program. Inside the main() function, you print the message “Sleeping…”, and then use await asyncio.sleep(3) to introduce a 3-second delay.

After the delay, you print the message “Done sleeping” to indicate that the delay is over.

To run the async IO program, you use asyncio.run(main()), which creates an event loop and runs the main() function until it completes.

When you run this code, you should see the message “Sleeping…” printed, followed by a 3-second delay, and then the message “Done sleeping” printed.

Using async IO can be a powerful way to write concurrent and asynchronous code in Python, and adding asyncio.sleep() can help introduce delays as needed.

In the next section, we’ll explore how to add a Python sleep() call with Graphical User Interfaces (GUIs).

Adding a Python sleep() Call With GUIs

Graphical User Interfaces (GUIs) allow users to interact with software using visual elements such as buttons, menus, and windows. When building GUI applications, adding a delay can be useful in scenarios such as animations or timed transitions between screens.

There are different libraries available in Python for building GUI applications, such as Tkinter and wxPython. We’ll explore how to add a sleep() call using these libraries.

Sleeping in Tkinter

Tkinter is a built-in Python library for creating GUI applications. To add a delay in Tkinter, you can use the after() method to schedule a function to run after a specified delay.

Here’s an example of how to use after() in Tkinter:

import tkinter as tk
def delayed_function():
print("Hello, after 5 seconds!")
root = tk.Tk()
root.after(5000, delayed_function) # Schedule the function to run after 5 seconds
root.mainloop()

In this example, you define a function delayed_function() that will be executed after a 5-second delay. You create an instance of tkinter.Tk() to create the main window for your GUI application.

Using the after() method with root.after(5000, delayed_function), you schedule the delayed_function() to run after 5 seconds.

Finally, you run the main event loop using root.mainloop() to start your GUI application. Once the specified delay has passed, the function delayed_function() will be executed, and you should see the message “Hello, after 5 seconds!” printed to the console.

Using the after() method in Tkinter allows you to add delays to your GUI applications and control the timing of different functions or actions.

Sleeping in wxPython

wxPython is another popular library for creating GUI applications. To add a delay in wxPython, you can use the wx.Timer class to schedule a function to run after a specified delay.

Here’s an example of how to use wx.Timer in wxPython:

import wx
def delayed_function(event):
print("Hello, after 5 seconds!")
app = wx.App()
frame = wx.Frame(None)
timer = wx.Timer(frame)
frame.Bind(wx.EVT_TIMER, delayed_function, timer)
timer.Start(5000) # Start the timer with a 5-second delay
app.MainLoop()

In this example, you define a function delayed_function(event) that will be executed after a 5-second delay. You create an instance of wx.App() to start the wxPython application, and wx.Frame(None) to create the main window.

Next, you create an instance of wx.Timer and bind it to the delayed_function() using frame.Bind(wx.EVT_TIMER, delayed_function, timer). This associates the timer with the function that you want to run after the delay.

Finally, you start the timer with timer.Start(5000), which sets the delay to 5 seconds. You run the main event loop using app.MainLoop() to start your GUI application. Once the specified delay has passed, the function delayed_function() will be executed, and you should see the message “Hello, after 5 seconds!” printed to the console.

Using the wx.Timer class in wxPython allows you to add delays to your GUI applications and control the timing of different functions or actions.

Conclusion

In this tutorial, you learned how to add time delays to your Python code using the sleep() function from the time module. You also explored different techniques for adding delays, such as using decorators, threads, async IO, and GUI libraries.

Introducing delays can be helpful in various scenarios, such as simulating a delay, coordinating actions, or preventing overloading of resources. By using the techniques covered in this tutorial, you can add time delays to your Python programs with ease.

So the next time you need to make your Python program wait, remember the sleep() function and its various applications!

Free Bonus: Get our free “The Power of Python Decorators” guide that shows you three advanced decorator patterns and techniques you can use to write cleaner and more Pythonic programs.