Add a time delay in Python
This post will discuss how to add a time delay in Python.
1. Using time.sleep() function
The standard way to add a time delay in Python is by calling the sleep() function from the time module. It works by suspending the execution of the calling thread for the specified number of seconds, which may be a floating-point value.
|
1 2 3 4 5 6 7 8 9 10 |
from time import sleep if __name__ == '__main__': delay = 1 # in seconds print('Go to sleep…') sleep(delay) print('Back to work…') |
2. Using threading.Event.wait function
Another alternative is to use the Event.wait function in the threading module. Here’s what the code would look like:
|
1 2 3 4 5 6 7 8 9 10 |
from threading import Event if __name__ == '__main__': delay = 1 # in seconds print('Go to sleep…') Event().wait(delay) print('Back to work…') |
3. Using threading.Timer class
If you need to delay the execution of a specific function instead of stopping the execution of the whole program, consider using the threading.Timer Python class, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
from threading import Timer def foo(delay): print(f'foo() called after {delay}s delay') if __name__ == '__main__': delay = 1 # in seconds print('Timer class demo') # call foo() after 1 second t = Timer(delay, foo, [delay]) t.start() print('foo() will be executed in 1 seconds…') |
That’s all about adding a time delay in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)