threading.Timer là subclass của Thread, chạy một hàm sau khoảng thời gian delay. Dùng cho scheduling một lần (one-shot).
Cú pháp
threading.Timer(interval, function, args=None, kwargs=None)
Ví dụ cơ bản: Chạy sau 3 giây
import threading
def my_timer():
print("Python Program")
timer = threading.Timer(3.0, my_timer)
timer.start()
print("Bye")
# Output (sau 3s):
# Bye
# Python Program
Hủy Timer
import threading
def my_timer():
print("Python Program")
timer = threading.Timer(3.0, my_timer)
timer.start()
print("Cancelling timer...")
timer.cancel() # Hủy trước khi chạy
print("Bye")
# Output:
# Cancelling timer...
# Bye
# (my_timer không chạy)
Lặp lại (Recurring Timer)
Timer chỉ chạy một lần. Để lặp, tự schedule lại trong callback:
import threading
def recurring_task():
print("Task running...")
# Schedule lại
threading.Timer(2.0, recurring_task).start()
# Khởi động
threading.Timer(2.0, recurring_task).start()
# Dừng sau 10s
import time
time.sleep(10)
print("Stopping...")
Lưu ý
- Timer tạo thread mới → overhead nếu lặp nhanh (dùng
schedhoặcAPScheduler). - Không chính xác real-time (phụ thuộc OS scheduler).
- Exception trong function không lan ra main thread.
- Daemon thread:
timer.daemon = Trueđể thoát chương trình không chờ.
So sánh
| Công cụ | Dùng cho | Độ chính xác |
|---|---|---|
| threading.Timer | One-shot, đơn giản | Thấp |
| sched.scheduler | Event loop đơn giản | Trung bình |
| APScheduler | Cron-like, persistent, distributed | Cao |
| asyncio.sleep | Async code | Tốt |