Skip to content

Python Pause: How to Effortlessly Pause Execution in Your Code

[

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

Table of Contents


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 behavior of time.sleep() was slightly changed. 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 make too many requests in a short amount of time, as that might appear as an attack on the server.

Here’s one way to implement such functionality using time.sleep():

import requests
import time
while True:
response = requests.get('https://www.example.com')
if response.status_code != 200:
print('Website is down!')
time.sleep(60) # Sleep for 60 seconds

In this example, the program repeatedly sends a GET request to https://www.example.com, checks if the response status code is not 200 (indicating a successful request), and prints a message if the website is down. Then, it waits for 60 seconds before making the next request. This allows for a delay between each request, giving the server some rest and preventing the program from overwhelming it with requests.

Using time.sleep() like this is a handy way to introduce a delay in your program when you need to wait for a specific amount of time before executing the next steps.

Now that you’ve learned how to add a sleep call using time.sleep(), let’s explore other methods of adding delays to your Python code.

Adding a Python sleep() Call With Decorators

Decorators are a powerful feature of Python that allow you to modify the behavior of a function or a class without changing its source code. You can also use decorators to add a sleep call to your functions, which can be useful in scenarios where you want to introduce a delay before or after a certain operation.

Here’s an example of how to create and use a decorator that adds a sleep call to a function:

import time
def sleep_decorator(function):
def wrapper(*args, **kwargs):
time.sleep(2) # Sleep for 2 seconds
return function(*args, **kwargs)
return wrapper
@sleep_decorator
def hello_world():
return 'Hello, world!'
print(hello_world())

In this example, the sleep_decorator function is a decorator that adds a sleep call of 2 seconds before executing the decorated function. The wrapper function is an inner function that wraps the original function and adds the sleep call. Finally, the @sleep_decorator syntax is used to apply the decorator to the hello_world function.

When you run this code, you’ll notice a delay of 2 seconds before the output is printed. The sleep call introduced by the decorator allows you to pause the execution of the function and control the timing of certain operations.

Decorators are a powerful tool in Python and can be used to modify the behavior of functions in various ways. Adding a sleep call to a decorator is just one example of how decorators can be useful in adding delays to your code.

Now that you’ve seen how to use decorators to add a sleep call, let’s explore more advanced methods of adding delays to your code.

Adding a Python sleep() Call With Threads

Threads in Python allow you to execute multiple tasks concurrently. This can be useful when you want to introduce delays without freezing the entire program. By using threads, you can perform certain operations in the background while the main program continues its execution.

There are multiple ways to add sleep calls using threads, depending on the specific requirements of your program. We’ll explore two common approaches: using time.sleep() and using Event.wait().

Using time.sleep()

One way to add sleep calls using threads is to use the time.sleep() function within a separate thread. This approach is useful when you want to pause the execution of a specific task without blocking the main thread.

Here’s an example that demonstrates how to use time.sleep() in a separate thread:

import threading
import time
def do_something():
print('Starting task...')
time.sleep(2) # Sleep for 2 seconds
print('Task completed.')
thread = threading.Thread(target=do_something)
thread.start()
print('Main thread continues executing...')

In this example, the do_something() function is defined to simulate some task that takes time to complete. The function uses time.sleep() to introduce a delay of 2 seconds before printing a completion message. The threading.Thread class is then used to create a separate thread that executes the do_something() function. Finally, the main thread continues its execution by printing a message.

When you run this code, you’ll notice that the main thread continues executing immediately after starting the separate thread. The sleep call within the separate thread allows the task to pause for 2 seconds without blocking the main thread.

Using threads in this way can be helpful when you need to perform time-consuming tasks without interrupting the flow of the main program. However, it’s important to be mindful of the potential issues that can arise when working with threads, such as race conditions and synchronization problems.

Using Event.wait()

Another way to add sleep calls using threads is to use the Event.wait() method provided by the threading module. This method allows you to pause the execution of a thread until a specific event occurs.

Here’s an example that demonstrates how to use Event.wait() to add a sleep call to a thread:

import threading
import time
def do_something(event):
print('Starting task...')
event.wait(2) # Wait for 2 seconds or until the event is set
print('Task completed.')
event = threading.Event()
thread = threading.Thread(target=do_something, args=(event,))
thread.start()
print('Main thread continues executing...')
time.sleep(1) # Sleep for 1 second
event.set() # Set the event to signal the thread to continue
thread.join() # Wait for the thread to finish before exiting the program

In this example, the do_something() function takes an event object as an argument. This event object is created using the threading.Event class. Within the function, the event.wait() method is used to pause the execution of the thread for 2 seconds or until the event is set. The main thread continues its execution after starting the separate thread and waits for 1 second before setting the event using the event.set() method. Finally, the main thread waits for the separate thread to finish using the thread.join() method before exiting the program.

When you run this code, you’ll notice that the main thread continues executing immediately after starting the separate thread. The event.wait() call within the separate thread allows the task to pause for 2 seconds or until the event is set.

Using Event.wait() can be helpful when you want to introduce conditional pauses in your code, allowing the thread to wait for certain events to occur before continuing its execution.

Now that you’ve learned how to add sleep calls using threads, let’s explore using Async IO to add delays to your code.

Adding a Python sleep() Call With Async IO

Async IO is a concurrency framework in Python that allows you to write asynchronous code in a synchronous style. It provides a way to handle I/O-bound operations efficiently and can be used to add delays to your code without blocking the event loop.

Here’s an example that demonstrates how to use Async IO to add a sleep call to your code:

import asyncio
async def do_something():
print('Starting task...')
await asyncio.sleep(2) # Sleep for 2 seconds
print('Task completed.')
asyncio.run(do_something())
print('Main program continues executing...')

In this example, the do_something() function is defined as an asynchronous coroutine using the async keyword. The asyncio.sleep() function is then used to introduce a delay of 2 seconds. The asyncio.run() function is used to run the coroutine and wait for it to complete. Finally, the main program continues executing after the coroutine finishes.

When you run this code, you’ll notice that the main program continues executing immediately after running the coroutine. The Async IO framework allows the coroutine to pause for 2 seconds without blocking the event loop.

Using Async IO can be helpful when you need to handle multiple I/O-bound tasks concurrently and want to introduce delays without blocking the execution of other tasks.

Now that you’ve learned how to add sleep calls using Async IO, let’s explore adding delays to GUI applications.

Adding a Python sleep() Call With GUIs

Graphical User Interfaces (GUIs) allow users to interact with applications using graphical elements such as buttons, menus, and windows. When developing GUI applications, you may need to introduce delays to control the timing of certain operations or simulate user interactions.

There are multiple ways to add sleep calls to GUI applications, depending on the specific GUI framework you’re using. In this section, we’ll explore how to add sleep calls using two popular GUI frameworks: Tkinter and wxPython.

Sleeping in Tkinter

Tkinter is a built-in GUI framework in Python that allows you to create simple graphical applications. You can use the time.sleep() function in combination with Tkinter’s after() method to introduce delays in your Tkinter applications.

Here’s an example that demonstrates how to use time.sleep() with Tkinter’s after() method:

import tkinter as tk
import time
def task():
print('Starting task...')
time.sleep(2) # Sleep for 2 seconds
print('Task completed.')
root = tk.Tk()
button = tk.Button(root, text='Start Task', command=task)
button.pack()
root.mainloop()

In this example, the task() function is defined to simulate a time-consuming task that takes 2 seconds to complete. The time.sleep() function is used to introduce a delay within the function. Tkinter’s Button widget is then used to create a button that, when clicked, executes the task() function. Finally, the Tkinter event loop is started using root.mainloop().

When you run this code, you can click the button to start the task. The sleep call within the task() function introduces a delay of 2 seconds before printing a completion message. During this time, the Tkinter event loop continues to process events and keep the application responsive.

Using time.sleep() with Tkinter’s after() method is a common way to introduce delays in Tkinter applications without affecting their responsiveness. However, it’s important to note that long sleep calls in the main thread can still make the GUI unresponsive, so it’s generally recommended to perform time-consuming tasks in separate threads or coroutines.

Sleeping in wxPython

wxPython is another popular GUI framework in Python that allows you to create cross-platform desktop applications. Similar to Tkinter, you can use the time.sleep() function to introduce delays in wxPython applications.

Here’s an example that demonstrates how to use time.sleep() in a wxPython application:

import wx
import time
class MyFrame(wx.Frame):
def __init__(self, parent, title):
super().__init__(parent, title=title)
self.panel = wx.Panel(self)
self.button = wx.Button(self.panel, label='Start Task')
self.button.Bind(wx.EVT_BUTTON, self.on_button_click)
def on_button_click(self, event):
print('Starting task...')
time.sleep(2) # Sleep for 2 seconds
print('Task completed.')
app = wx.App()
frame = MyFrame(None, title='Sleep Example')
frame.Show()
app.MainLoop()

In this example, a custom MyFrame class is defined that inherits from wxPython’s Frame class. The MyFrame class creates a button that, when clicked, executes the on_button_click() method. The sleep call within the on_button_click() method introduces a delay of 2 seconds before printing a completion message.

When you run this code, you can click the button to start the task. The sleep call within the on_button_click() method introduces a delay of 2 seconds before printing a completion message. During this time, the wxPython event loop continues to process events and keep the application responsive.

Using time.sleep() in wxPython applications is a simple way to introduce delays. However, similar to Tkinter, long sleep calls in the main thread can still make the GUI unresponsive. It’s generally recommended to perform time-consuming tasks in separate threads or coroutines.

Now that you’ve learned how to add sleep calls to GUI applications, let’s wrap up this tutorial.

Conclusion

In this tutorial, you’ve learned how to add sleep calls to your Python code using various methods. You learned how to use time.sleep() to pause the execution of your program for a specified amount of time. You also explored how to add sleep calls using decorators, threads, Async IO, and GUI frameworks.

By adding sleep calls to your Python code, you can introduce delays for a variety of purposes, such as simulating real-world timing, controlling the flow of your program, or coordinating concurrent tasks. You can now incorporate these sleep calls into your own projects and take advantage of the various techniques covered in this tutorial.

Remember to be mindful of how sleep calls can affect the overall performance and responsiveness of your program. If used incorrectly, long sleep calls can make your program feel slow or unresponsive. It’s important to consider the specific requirements of your program and choose the most appropriate method for adding delays.

We hope this tutorial has provided you with the knowledge and tools you need to add sleep calls to your Python code effectively. Keep practicing and exploring different use cases for sleep calls, and you’ll continue to improve your Python skills. Happy coding!