Have you ever needed to wait for something in your Python program? You want your code to run as rapidly as possible most of the time. However, there are occasions when putting your code to sleep is in your best interests.
To mimic a delay in your software, for example, you may use the Python sleep() function. It’s possible that you’ll have to wait for a file to upload or download, or for a graphic to load or be rendered on the screen. You might even need to take a break between calls to a web API or database queries. In each of these scenarios, and many others, adding Python sleep() calls to your application will assist!
The sleep() method suspends (waits) the current thread’s execution for a specified number of seconds.
Python offers a time module that contains various helpful methods for dealing with time-related activities. One of the popular functions among them is sleep().
The sleep() method suspends the current thread’s execution for a specified amount of seconds.
Python Sleep/Wait 1 Second
import time
# Wait for 5 seconds
time.sleep(5)
# Wait for 300 milliseconds
# .3 can also be used
time.sleep(.300)
Code language: CSS (css)
How To Wait In Python Script
import time
#Waits 1 second
time.sleep(1)
Code language: CSS (css)
Python Time Delay
import time
while True:
print("This prints once a minute.")
time.sleep(60) # Delay for 1 minute (60 seconds).
Code language: PHP (php)
Sleep Function Python
import time
print("Printed immediately.")
time.sleep(2.4)
print("Printed after 2.4 seconds.")
Code language: PHP (php)
Delay Time Python
import time
time.sleep(5) # sleeps for 5 seconds
Code language: CSS (css)
How to Add Time Delays to Your Python Code
import time
print("Print now")
time.sleep(4.2)
print("Printing after 4.2 seconds")
Code language: PHP (php)
Python Sleep In Multithreaded Programs
The sleep() method suspends the current thread’s execution for a specified amount of seconds.
Sleep() suspends the thread and process execution in single-threaded programs. In multithreaded systems, however, the function suspends a thread rather than the entire process.
import threading
import time
def print_hello():
for i in range(4):
time.sleep(0.5)
print("Hello")
def print_hi():
for i in range(4):
time.sleep(0.7)
print("Hi")
t1 = threading.Thread(target=print_hello)
t2 = threading.Thread(target=print_hi)
t1.start()
t2.start()
Code language: JavaScript (javascript)
There are two threads in the above application. We’ve made use of time. To suspend execution of these two threads for 0.5 seconds and 0.7 seconds, respectively, using time.sleep(0.5)
and time.sleep(0.75)
.
Conclusion
In this article, we learned the fundamentals of python sleep function and how to use it to implement delay/sleep feature into our python scripts. As always, If you have found this article useful do not forget to share it and leave a comment if you have any questions. Happy Coding 🙂
Leave a Reply
You must be logged in to post a comment.