Python sleep – How to Pause,Wait, Stop or Sleep Your Code in Python ?

Python sleep() : In this tutorial we will see how to pause his python program. There are times when letting your code sleep for a period of time is actually helpful. For example, if you make a lot of calls to a Web API, it may be a good idea to pause the program for a few seconds to avoid reaching the restrictions on the maximum number of calls to an api. There are different python libraries that allow you to do this.
- time.sleep()
- Threads
- Async IO
In the rest of the article I will detail each of them. Here we go! 🙂
Python sleep()
using time module
Python time sleep function is used to add a delay in the execution of a program. The python sleep function can be used to stop program execution for a certain amount of time (expressed in seconds). This function only stops the current thread, so if your program contains multiple threads, the other threads will continue to run.
time.sleep() syntax
the sleep() function is available in time module. The first thing to do to use the function is to import the time module. Here is the code to use the function :
# importing time module
import time
print("Hello Everyone ! ")
time.sleep(5)
print("Hello? Anybody there?")
Python sleep example
Here is an example of the sleep function:
import time
runs = ["On your marks", "Get set","Go!"]
startTime = time.time()
for r in runs:
print(r)
time.sleep(1)
endTime = time.time()
elapsedTime = endTime - startTime
print("Elapsed time for race start : %s" % elapsedTime)
Output: On your marks Get set Go! Elapsed time for race start : 3.001661777496338
As you can see in the example, at each step there is a 1 second pause. The time() function returns the number of seconds passed since epoch. We can see that the elapsed time is slightly more than 3seconds, this is quite normal since the execution of the loop also takes some time to run.
Set the delay of the time() function
In some cases, it may be useful to set a more or less important delay than the default value of 1 second. In the example below, we will change this value by 0.5 seconds (500 milliseconds) :
import time
runs = ["On your marks", "Get set","Go!"]
startTime = time.time()
for r in runs:
print(r)
time.sleep(0.5)
endTime = time.time()
elapsedTime = endTime - startTime
print("Elapsed time for race start : %s" % elapsedTime)
Output: On your marks Get set Go! Elapsed time for race start : 1.5017940998077393
As can be seen in the example, the execution time has been reduced from about 3 seconds to 1.5 seconds.
Python thread sleep
In many cases, you can use the sleep() function in combination with threads. This is a very important function in multi-threading. Here is an example that uses multiple threads to which we added a pause with a different delay :
from threading import Thread
import time
website="AMIRADATA"
class first(Thread):
def run(self):
for l in website:
time.sleep(0.5)
print("Give me a "+l+" !")
class second(Thread):
def run(self):
time.sleep(5)
print(website+ " ! ")
first().start()
second().start()
Output: Give me a A ! Give me a M ! Give me a I ! Give me a R ! Give me a A ! Give me a D ! Give me a A ! Give me a T ! Give me a A ! AMIRADATA !
The first thread will print each character of the “website” string and the second thread will print the whole string.
Using wait() function
The threading module also has its own function called wait(). The principle reason for using this function is that the function is non-blocking while the time.sleep() function is blocking. This means that when you use time.sleep(), you prevent the main thread from continuing to execute while it waits for the sleep() end of the call.
from threading import Thread
import threading
website="AMIRADATA"
class first(Thread):
def run(self):
for l in website:
event.wait(0.5)
print("Give me a "+l+" !")
class second(Thread):
def run(self):
event.wait(5)
print(website+ " ! ")
event = threading.Event()
first().start()
second().start()
This produces the same output as using time.sleep(). Just keep in mind that the wait() function is non-blocking. If you want to know more about threads and the use of events I invite you to consult the python documentation on the subject! 🙂
AsyncIO Module
In version 3.4 of python, new features have been integrated. Asynchronous programming is a parallel programming that allows you to execute several tasks simultaneously. When one of these tasks is completed, it informs the main thread.
the asyncio module is a module that allows you to call a sleep() but works asynchronously. Please refer to the documentation for more information.
Here is a simple example of how to use the asyncio module :
import asyncio
runs = ["On your marks", "Get set","Go!"]
async def races():
for r in runs:
print(r)
await asyncio.sleep(1)
asyncio.run(races())
Output: On your marks Get set Go!
We are obliged to use the keyword await since we have declared the function as asynchronous (we have to add the keyword async in its function declaration).
Conclusion
As you can see, there are several ways to stop or pause your python program. Each solution answers different problems, so it depends on your use cases. I hope you liked this tutorial (if you did, feel free to tell me about it in the comments 🙂 )
Comments
Leave a comment