Problem Statement: How can I make a time delay in Python?
Normally when you are coding, you want to execute the code and get the output immediately without any delay or discontinuity. However, there can be situations wherein you want to delay the execution of a certain piece of your code. For example, let’s say that you want to visualize the effect of multithreading with the help of a code. In this case, a slight time delay between the respective threads in the program can help you to better visualize the output and thereby enhance your understanding. So, this is when time delay becomes an extremely useful tool.
You can use the time delay function between any two statements or between any part of the program as per your requirement. You can also use the time delay when you are waiting for any other process to complete, e.g., a file to upload.
Now, let’s have a look at the different methods to incorporate time delay in our Python code.
Method 1: Using sleep() Method of Time Module
sleep() is a built-in method of the
time module in Python that is used to delay the execution of your code by the number of seconds specified by you. Let’s have a look at the syntax of the sleep method –
time.sleep(value in seconds)
Here, the delay in time can be passed as a parameter to the
sleep method, which specifies the number of seconds by which you want to delay your script. Also, note that you must import the
time module so that you can use its sleep method in your code.
Example 1: Creating a time delay of 6 seconds between two print statements.
import time print(" Hello Folks! Welcome to FINXTER!") time.sleep(6) print(" This gets printed after 6 seconds!")
TIDBIT: You can use the time.sleep() method to print messages in the string as if the compiler is auto typing. It is known as Dynamic printing.
Try to execute the following snippet in your compiler 😉
import time st = "Hey Finxter! Welcome to the journey to master Python!" for i in st: print(i, end="") # Making a time delay of 1 second time.sleep(0.5)
Method 2: Using sleep() Method of Asyncio Library
If you are using Python 3 or above, then there’s another library that provides the sleep method and can be used for the purpose of implementing time delay in our script. The name of this library is Asyncio.
Here’s what the official documentation says about the asyncio library –
Well, let’s have a look at an example to understand the working of the sleep method of the asyncio library.
# Importing the asyncio library import asyncio print("Hello Folks! Welcome to FINXTER!") # Starting the code using async async def show(): await asyncio.sleep(6) print("This gets printed after 6 seconds!") asyncio.run(show())
Difference between time.sleep and asyncio.sleep
The difference between
asyncio.sleep is that generally the
time.sleep() function is used for the purpose of blocking, and asyncio.sleep() is used for non-blocking. This means that the
time.sleep() function blocks the entire execution of the script when it gets called, and the script gets put on hold while doing nothing. However, when you call
asyncio.sleep() function asks the event loop to run something else while the
await statement finishes its execution.
Here’s an example –
import asyncio async def foo(): print('Executing A') await asyncio.sleep(5) print('Executing B') async def main(): await asyncio.gather(foo(), foo()) print("asyncio.sleep() in Operation!") asyncio.run(main())
asyncio.sleep() in Operation! Executing A Executing A Executing B Executing B
asyncio.sleep() does not block the entire script hence the first print statements for the foo() method get executed as foo() is called twice. Hence, the output is as shown above. In case the script was blocked, then the script would wait and print each print statement for the respective function calls before moving on to the next call.
Method 3: Using Event.wait()
Event.wait() is a function of the threading module in Python. The function is used to delay the execution of any process for the number of seconds that it takes as an argument. Event class is used to generate the events where any single event can be listened to by multiple threads.
# Importing Event from the threading module from threading import Event print(" Hello Folks! Welcome to FINXTER!") Event().wait(5) print(" This gets printed after 6 seconds")
Method 4: Using Timer
Timer is another method from the
threading module that is used to implement time delay in Python. The method is used to run and execute the operations only after a certain period has passed, thereby delaying the execution. To start the timer function, you have to call the
start() method. The method accepts two parameter values where the first one denotes the number of seconds to wait before executing the code and the second parameter denotes a function that you need to run after the specific time.
|Timer(value in seconds, function)|
# Importing Timer from the threading module from threading import Timer print(" Hello and Welcome to Finxter") def show(): print("This gets printed after 7 seconds") # Calling the timer method t = Timer(7, show) t.start()
Hello and Welcome to Finxter This gets printed after 7 seconds
You can even halt the timer method by calling
cancel(). You can use this function when you have many functions running and you want to cancel the execution of a single function based on the results of another function.
# Importing Timer from the threading module from threading import Timer def show(): res = func1() t = Timer(5, func2) t.start() if(res < 5): print("Cancel the func3 as func2 resulted in", res) t.cancel() def func2(): print("The second function gets executed") return random.randint(1, 10) def func3(): print("Third function gets executed") show()
(Case 1- If the func2 returns number less than 5) Output:
|The second function gets executed|
Cancel the func3 as func2 resulted in 3
(Case 2- If the func2 returns a number greater than 5) Output:
|The second function gets executed|
Third function gets executed
In this article we discussed numerous ways to implement time delays in your Python code. I hope it has helped to answer your queries. Please subscribe and stay tuned for more interesting articles in the future.
- One of the most sought-after skills on Fiverr and Upwork is web scraping. Make no mistake: extracting data programmatically from websites is a critical life skill in today’s world that’s shaped by the web and remote work.
- So, do you want to master the art of web scraping using Python’s BeautifulSoup?
- If the answer is yes – this course will take you from beginner to expert in Web Scraping.