Hi Pythonistas!
Today I’m sharing a Python trick that feels like setting a timer on your code. If you’ve ever wished you could run a function after a delay, but without blocking your main thread, you’ll love threading.Timer.
Why Not Just Use time.sleep()?
import time
time.sleep(5)
print("Hello after 5 seconds")
✅ Simple
❌ But blocks the whole program
If you're building a UI, a server, or anything interactive blocking is bad.
✅ The Better Way: threading.Timer
from threading import Timer
def greet():
print("Hello after 5 seconds!")
t = Timer(5.0, greet)
t.start()
print("Timer started... you can do other things now.")
- Runs greet() after 5 seconds
- Non-blocking
- Great for reminders, retries, background tasks
You Can Cancel the Timer Too
t = Timer(10.0, greet)
t.start()
t.cancel()
Useful for retries, user cancellations, or debounce logic.
Use Cases
- Retry a failed network request after delay
- Timeout notifications
- UI tooltips that disappear after a few seconds
- Debounce behavior in CLI or games
time.sleep() blocks — ❌ bad for responsiveness
threading.Timer() delays function execution — ✅ clean and async
You can even cancel a scheduled function before it runs!
Bonus: Loop with Delayed Execution?
from threading import Timer
def repeat():
print("Tick")
Timer(2.0, repeat).start()
repeat()
This creates a lightweight, self-repeating timer.
I hope you have learned something from this post. Please share your valuable feedbacks with afsal@parseltogue.co.in