The sleep() in Python is defined in the time() module of Python 3 and 2 versions. However, in some cases, there is a requirement to halt the execution program so that several other executions can occur or only due to the required utility. Python sleep() can come in handy in such a situation; that provides an accurate and flexible way to halt the flow of code for any period.
Python sleep
Python sleep() is a built-in time module function that suspends (waits) execution of the current thread for a given number of seconds. The time.sleep() function is equivalent to the Bash shell’s sleep command. Almost all programming languages have this feature, which is used in many use-cases.
Python has a time module that provides several useful functions to handle time-related tasks, one of which is sleep(). The sleep() function suspends the current thread’s execution for a given number of seconds.
Syntax
time.sleep(secs)
It takes an argument called secs. It is the number of seconds a Python program should pause execution. This argument should be either an int or float.
See the following code example.
# app.py import time # Wait for 3 seconds time.sleep(3) print('After 3 secs')
See the following output. It will print the statement after 3 secs.
➜ pyt python3 app.py After 3 secs ➜ pyt
Python create a digital clock
To create a digital clock in Python,
import time while True: localtime = time.localtime() result = time.strftime("%I:%M:%S %p", localtime) print(result) time.sleep(1)
In the above code, we have used the while loop.
See the following output.
➜ pyt python3 app.py 01:12:30 PM 01:12:31 PM 01:12:32 PM 01:12:33 PM 01:12:34 PM
The different delay times of python sleep()
In some cases, you may need to delay for different seconds. See the following example.
# app.py import time for t in [ .3, .2, 1, 3]: print("Waiting for %s" % t , end='') print(" seconds") time.sleep(t)
See the following output.
➜ pyt python3 app.py Waiting for 0.3 seconds Waiting for 0.2 seconds Waiting for 1 seconds Waiting for 3 seconds ➜ pyt
Python thread sleep
Python time sleep() function is a critical method for multithreading.
See the following example.
# app.py import time from threading import Thread class Atapi(Thread): def run(self): for x in range(1, 12): print(x) time.sleep(1) class Vatapi(Thread): def run(self): for x in range(100, 105): print(x) time.sleep(5) print("Staring Atapi Thread") Atapi().start() print("Starting Vatapi Thread") Vatapi().start() print("Completed")
See the following output.
➜ pyt python3 app.py Staring Atapi Thread 1 Starting Vatapi Thread 100 Completed 2 3 4 5 101 6 7 8 9 10 102 11 103 104 ➜ pyt
From the output, it’s evident that only the threads are being stopped from execution and not the whole program by the python time sleep function.
That’s it for this tutorial.