Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Đối tượng Timer trong Python (threading.Timer)

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 sched hoặc APScheduler).
  • 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.TimerOne-shot, đơn giảnThấp
sched.schedulerEvent loop đơn giảnTrung bình
APSchedulerCron-like, persistent, distributedCao
asyncio.sleepAsync codeTốt