Hello everyone! In this post, we’ll look at how we can wait for a specific time in Python.
This is particularly important when you have certain events or tasks scheduled after a specific period of time.
Python offers us different ways to do this. So let’s look at all the approaches that we can use: both in a single-threaded as well as a multi-threaded environment!
Python – Wait for a Specific Time in Single-Threaded Environments
If your main program consists only of a single thread / program, then Python makes this very easy for us.
One possible approach to make a program wait for a specific time in Python is using the time module.
Using time.sleep() to wait
We can use time.sleep(n)
to wait for n
seconds. Of course, we can make n
to be decimal to be more precise with our interval!
Here is a simple example, which schedules two function calls between 3 seconds within each other.
import time
def fun1(a):
return 2 * a
def fun2(a):
return a * a
if __name__ == '__main__':
inp = 10
print(f"Input = {inp}")
print(f"Result of fun1 call: {fun1(inp)}")
time.sleep(3) # Wait for 3 seconds
print(f"After 3 milliseconds, Result of fun2 call: {fun2(inp)}")
Output
Input = 10
Result of fun1 call: 20
After 3 seconds, Result of fun2 call: 100
Simple enough, right?
Waiting in a Multi-Threaded Environment
If you’re having multiple threads in your program, you can still use the same logic via time.sleep()
to make a particular thread wait for a specific time in Python
Here is an example, which spawns 3 threads, and makes them sleep for a second alternatively, while the other threads keep printing numbers from 1.
We’ll use the concurrent.futures
module and use the ThreadPoolExecutor
to pool and execute threads, while fetching the results using as_completed()
.
The basic structure of spawning and fetching using threads is as follows:
from concurrent.futures import ThreadPoolExecutor, as_completed
# The threads will call this function
def callback():
pass
with ThreadPoolExecutor() as thread_executor:
# Await all results
await_results = [thread_executor.submit(callback) for i in range(1, tid+1)]
# Fetch them!
for f in as_completed([future for future in await_results]):
print(f.result())
Now, let’s write the code for our main program.
from concurrent.futures import ThreadPoolExecutor, as_completed
import time
# Global Variable for the Thread ID Number
tid = 0
# Spawn 4 threads
NUM_THREADS = 4
def func(arg):
time.sleep(1)
return arg * arg
if __name__ == '__main__':
with ThreadPoolExecutor() as thread_executor:
start_time = time.time()
# Going to spawn threads
tid += NUM_THREADS
# Await all results
await_results = [thread_executor.submit(func, arg=i) for i in range(1, tid+1)]
for f in as_completed([future for future in await_results]):
print(f.result())
end_time = time.time()
print(f"Total Time taken for {NUM_THREADS} threads: {end_time - start_time}")
Output
1
4
9
16
Total Time taken for 4 threads: 1.0037879943847656
As you can see, we spawned 4 threads, who all waited for 1 second before giving the result of the function. This is very close to 1 second, so our output makes sense!
Using threading.Timer() to schedule function calls
However, if you want a particular function to wait for a specific time in Python, we can use the threading.Timer()
method from the threading
module.
We’ll show a simple example, which schedules a function call every 5 seconds.
from threading import Timer
import time
def func(a, b):
print("Called function")
return a * b
# Schedule a timer for 5 seconds
# We pass arguments 3 and 4
t = Timer(5.0, func, [3, 4])
start_time = time.time()
# Start the timer
t.start()
end_time = time.time()
if end_time - start_time < 5.0:
print("Timer will wait for sometime before calling the function")
else:
print("5 seconds already passed. Timer finished calling func()")
Output
Timer will wait for sometime before calling the function
Called function
Here, the main program came to the last line before 5 seconds were up, so Timer makes the program wait until it calls func()
.
After calling func(a, b)
, it terminates the program, since there is nothing else to run.
Also notice that the return value of the function cannot be used by the main program.
Hopefully, this gave you some more ideas about scheduling and waiting for intervals.
Conclusion
In this article, we learned about waiting for a specific period of time in Python, using time.sleep()
. We also saw how we could use this in a Multi-Threaded environment, as well as scheduling function calls.
References
- Python Docs on Threading Timer
- StackOverflow Question on creating time delays