Advanced Python 14 — Timers, Scheduled Execution, Timeout Patterns
Sometimes we don’t want a thread to run immediately.
You may want:
- “Run this after 5 seconds”
- “Cancel this if not needed”
- “Stop waiting after a timeout”
Python provides a clean solution: threading.Timer
What is threading.Timer?
A Timer is a thread that:
✔ Waits for a specified time
✔ Then runs a function
import threading
def say_hello():
print("Hello after 3 seconds!")
timer = threading.Timer(3, say_hello)
timer.start()What happens?
- Timer starts
- Waits 3 seconds
- Calls
say_hello()
Canceling a Timer
timer.cancel()import threading
import time
def task():
print("This should not run")
timer = threading.Timer(5, task) # Task function will run after 5 milliseconds
timer.start()
time.sleep(2)
timer.cancel() # Timer cancelled after 2 milliseconds
print("Timer canceled")
'''Output:
Timer canceled
'''Scheduled Execution Using Timer
Timers are useful for scheduled tasks.
Running Something Later
def reminder():
print("Time’s up!")
threading.Timer(10, reminder).start()Repeating Tasks (Important Pattern)
threading.Timer runs only once.
Get Abhishek Jain’s stories in your inbox
Join Medium for free to get updates from this writer.
To repeat, we reschedule inside the function.
import threading
def repeat_task():
print("Running task...")
threading.Timer(2, repeat_task).start()
repeat_task()Task runs every 2 seconds
Be careful:
- This creates new threads repeatedly
- Good for light tasks
- Not ideal for high-frequency loops
Timeout Patterns (Very Useful)
Timeout = “Stop waiting if it takes too long”
Timeout While Waiting for Something
We combine:
EventTimer
import threading
import time
event = threading.Event()
def timeout_handler():
print("Timeout occurred!")
event.set()
# Start timeout timer
threading.Timer(5, timeout_handler).start()
print("Waiting for event...")
event.wait()
print("Done")
'''Output:
Waiting for event...
Timeout occurred!
Done
'''Timeout for a Worker Thread
Example: Stop long task
import threading
import time
shutdown_event = threading.Event()
def worker():
print("Worker started")
time.sleep(10) # long work
if not shutdown_event.is_set():
print("Worker finished")
else:
print("Worker not finished")
def timeout():
print("Too slow! Shutting down...")
shutdown_event.set()
threading.Timer(3, timeout).start()
t = threading.Thread(target=worker)
t.start()
t.join()
'''Output:
Worker started
Too slow! Shutting down...
Worker not finished
'''Function Execution Timeout (Guard Pattern)
Goal:
Run a function, but detect if it takes too long.
️Important:
We do NOT kill the thread (unsafe).
We guard and react instead.
import threading
import time
finished_event = threading.Event()
def long_task():
print("Task started")
time.sleep(5) # simulate slow work
print("Task completed")
finished_event.set()
# Run task in a separate thread
t = threading.Thread(target=long_task)
t.start()
# Wait with timeout
if not finished_event.wait(timeout=2):
print("Timeout! Task is taking too long...")
else:
print("Task finished within time")
t.join()
''' Output:
Task started
Timeout! Task is taking too long...
Task completed
'''When Should You Use threading.Timer?
Use it for:
✔ Delayed tasks
✔ Reminders
✔ Timeouts
✔ Scheduled execution
Avoid it for:
❌ High-precision scheduling
❌ Very frequent repetition









