In Python programming, controlling execution timing can be essential, whether for managing API calls, pacing thread executions, or controlling output display in terminal applications. The mainstay for introducing pauses in your code is the time.sleep() function. It's your go-to tool when you need to halt the execution of your program for a specified duration:
from time import sleep
sleep(3) # Pause execution for 3 seconds
While time.sleep() is straightforward, Python also offers various methods for introducing time delays, each serving specific use cases like threading, asynchronous programming, and graphical user interfaces.
By the end of this discussion, you'll appreciate the following:
time.sleep()pauses execution for a specified number of seconds, supporting fractional seconds for precise delays.- Retry decorators apply
time.sleep()to introduce delays between failed attempts for robust error handling. Event.wait()provides a more interruptible pause in threaded applications.asyncio.sleep()enables pausing a coroutine without blocking other asynchronous activities.- GUI frameworks such as Tkinter boast scheduling functions like
.after()to prevent freezing in event loops.
Let's explore each of these strategies with live coding examples to illustrate their practical applications.
Get Your Code: Download the sample code useful for implementing time delays in scripts, threads, async routines, and GUIs.
Using Python's sleep() to Pause Execution
Python's time module includes a method with which you can cause your program to wait. The sleep() function permits specifying a pause duration in seconds:
>>> import time
>>> time.sleep(3) # Sleep for 3 seconds
Here's a brief example showcasing time.sleep() in action:
coffee.py
import time
print("Brewing coffee...")
print("This will take about 3 seconds...")
time.sleep(3)
print("Done! Your coffee is ready!")
If you execute this script, you'll witness a three-second pause between the outputs as time.sleep() holds the program's execution.
Providing fractional seconds to time.sleep() allows for more precise control over delays. Here are some common values:
import time
time.sleep(0.5) # Wait 500 milliseconds
time.sleep(0.001) # Wait 1 millisecond
time.sleep(1.5) # Wait 1.5 seconds
time.sleep(60) # Wait 1 minute
While time.sleep() is generally reliable, it's important to understand that the specified delay serves as a minimum; actual pauses may exceed this duration due to system scheduling and load.
To measure execution time accurately, use Python's timeit module:
$ python -m timeit -n 3 "import time; time.sleep(3)"
3 loops, best of 5: 3 sec per loop
In this instance, you invoke the timeit module with the -n option, specifying how often the statement should run in each repeat. The default configuration executes the statement multiple times, yielding reliable timing results, such as three seconds per loop in this case.
Consider a practical scenario where you want to monitor a website's uptime without overwhelming the server or risking rate limits. You can effectively implement time.sleep() to regulate the intervals between your checks:
uptime_bot.py
import time
import urllib.request
import urllib.error
CHECK_INTERVAL = 60 # Seconds between checks
def uptime_bot(url):
while True:
try:
urllib.request.urlopen(url)
except urllib.error.HTTPError as e:
# Email admin or log
print(f"HTTPError: {e.code} for {url}")
except urllib.error.URLError as e:
# Email admin or log
print(f"URLError: {e.reason} for {url}")
else:
# Website is up
print(f"{url} is up")
time.sleep(CHECK_INTERVAL)
if __name__ == "__main__":
url = "https://www.google.com/py"
uptime_bot(url)
Using time.sleep() in this context helps in regulating how frequently the server is queried, thus minimizing the risk of causing overload or hitting rate limits.
Read the complete article at https://realpython.com/python-sleep/ ยป
[ Improve Your Python With ๐ Python Tricks ๐ โ Get a Python Trick delivered to your inbox every few days. >> Click here to learn more and access examples ]