Effortlessly Master the Python Wait Command
Python sleep(): How to Add Time Delays to Your Code
By Mike Driscoll
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!
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()
:
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:
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 cause issues for the website by checking too often. To address this, you can add a sleep call in your code to introduce a delay between checks:
In this example, the code checks the status code of the website and prints a message accordingly. Then it sleeps for 60 seconds before checking again. This code allows for periodic checks without overwhelming the website with requests.
Adding a Python sleep()
Call With Decorators
In addition to using time.sleep()
, you can also use decorators to add sleep functionality to your code. A decorator is a design pattern in Python that allows a user to apply additional functionality to an existing function.
Here’s an example of how to create a decorator that adds a sleep functionality to a function:
In this example, the sleep_decorator
function is defined, which takes another function func
as an argument. Inside the wrapper
function, time.sleep(2)
is used to introduce a 2-second delay before calling the original func
. The wrapper
function is then returned as the modified function.
The @sleep_decorator
line before the print_hello
function definition applies the sleep_decorator
to the print_hello
function. When you call print_hello()
, it will execute the sleep functionality defined in the decorator before printing “Hello!“.
This is just a basic example of how you can use decorators to add sleep functionality to your code. You can customize the decorator to add different types of delays and implement more complex functionality.
Adding a Python sleep()
Call With Threads
Another way to add sleep functionality to your code is by using threads. Threads allow you to run multiple parts of your program concurrently, which can be useful when creating programs with long-running operations.
Here’s an example of how to use threads to introduce a sleep functionality:
In this example, the sleep_function
and other_function
are defined. The sleep_function
contains the sleep functionality, which introduces a 2-second delay before printing the second message. The other_function
simply prints a message.
The Thread
class from the threading
module is used to create two separate threads for each function. The start()
method is called on each thread to begin executing the functions concurrently. The join()
method is used to wait for both threads to finish executing before the program exits.
Using threads can be helpful when you want to introduce sleep functionality to your program without blocking the rest of the code from executing. This can be particularly useful when dealing with time-consuming operations or when you want to add parallelism to your code.
Adding a Python sleep()
Call With Async IO
Python’s asyncio
module provides support for asynchronous programming. Asynchronous programming allows parts of your code to execute concurrently, which can be helpful for improving the performance and responsiveness of your program.
Here’s an example of how to use asyncio.sleep()
to introduce a sleep functionality in an asynchronous program:
In this example, the sleep_function
and other_function
are defined as async functions. The sleep_function
uses asyncio.sleep(2)
to introduce a 2-second delay before printing the second message. The other_function
simply prints a message.
The asyncio.create_task()
function is used to create tasks for each function, which allows them to run concurrently. The tasks are awaited using the await
keyword to wait for both tasks to finish executing before the program exits.
Using async IO can be beneficial when you want to introduce sleep functionality to your program without blocking the execution of other code. It allows you to write asynchronous code that is more efficient and responsive.
Conclusion
In this tutorial, you learned various ways to add sleep functionality to your Python code. Adding delays can be useful in a variety of scenarios, such as simulating delays, controlling the timing of program execution, or improving program performance.
You learned how to use time.sleep()
to introduce delays, as well as how to create decorators to add sleep functionality to functions. Additionally, you explored using threads and async IO to introduce sleep functionality to concurrent code.
By mastering the use of sleep()
in Python, you can create more robust and efficient code that better suits your needs. Experiment with the different methods explained in this tutorial to see which approach works best for your specific use cases.