Python sleep () is one of the most popular functions that come along with the Python module called time. The sleep () in Python is a handy function that can be used by the developers to halt their python codes for any specified period of time.
Importance of Python sleep function
Most of the programmers want their codes to execute as fast as possible. But do you think of a programmer encountered with a need to make your Python program wait for something? There are some cases a programmer’s best interest would be to make the code sleep in the python program. Sometimes it is required to halt the flow of the program so that several other executions can take place or simply due to the utility required.
For example, a programmer might use this function to simulate a delay in the python program. Maybe the programmer needs to wait for some file uploads or downloads to complete or for some graphics components to be loaded or drawn on the screen. Sometimes, programmers even want to halt their programs between calls of web API, or between queries to a database. Adding Python sleep in python programs is essential for programmers in each of such cases and many more.
Syntax of Python sleep function
Since the sleep function is a built-in that comes with the Python time module, before using sleep () in Python code, the time should be imported. Below is an example of how to write sleep in python:
# import library time >>> import time # Sleep for 5 seconds >>> time.sleep(5)
If the above code is run in a console, then a significant delay should be experienced before able to enter a new statement.
In Python 3.5, the core programmers enhanced the behavior of sleep function slightly. The new function call will last at least the number of seconds specified, even some signal interrupts the sleep in python code. However, this does not work, if the signal itself causes an exception.
Demonstration of Python sleep function with an example
# Python code to demonstrate the working of sleep() import time # print the start time print("The start time of code execution is : ", end ="") print(time.ctime()) # using sleep() function to hault the code execution time.sleep(5) #### OUTPUTS The start time of code execution is : Mon May 2 20:57:10 2020 The end time of code execution is : Mon May 2 20:57:16 2020
If you want to learn more about it, please check this Youtube video: