Timer objects ใช้สร้าง actions ที่ถูกจำกัดโดยช่วงเวลา สร้าง thread ที่ทำงานหลังจากเวลาที่กำหนด ใน Python Timer เป็น subclass ของ Thread ใช้เมธอด start() เริ่มจับเวลา
Syntax
threading.Timer(interval, function, args=None, kwargs=None)
interval- เวลาเป็นวินาที (float)function- ฟังก์ชันที่จะเรียกเมื่อเวลาครบargs- tuple ของ positional argumentskwargs- dict ของ keyword arguments
ตัวอย่างที่ 1: Timer พื้นฐาน
import threading
def mytimer():
print("Python Program")
# สร้าง timer 3 วินาที
my_timer = threading.Timer(3.0, mytimer)
my_timer.start()
print("Bye")
ผลลัพธ์
Bye
Python Program
"Bye" พิมพ์ทันที "Python Program" พิมพ์หลัง 3 วินาที
ตัวอย่างที่ 2: ยกเลิก Timer (Cancel)
ใช้ timer.cancel() หยุด timer ก่อนที่จะทำงาน
import threading
def mytimer():
print("Python Program")
my_timer = threading.Timer(3.0, mytimer)
my_timer.start()
print("Cancelling timer")
my_timer.cancel() # ยกเลิกก่อน 3 วินาที
print("Bye")
ผลลัพธ์
Cancelling timer
Bye
"Python Program" ไม่ถูกพิมพ์ เพราะ timer ถูกยกเลิก
ตัวอย่างที่ 3: Timer พร้อม Arguments
import threading
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
# Timer 2 วินาที พร้อม args และ kwargs
t = threading.Timer(2.0, greet, args=("World",), kwargs={"greeting": "Hi"})
t.start()
print("Timer started...")
ผลลัพธ์
Timer started...
Hi, World!
ตัวอย่างที่ 4: Repeating Timer (ทำซ้ำ)
Timer ทำงานแค่ครั้งเดียว ถ้าต้องการทำซ้ำ ต้องสร้าง timer ใหม่ใน callback
import threading
def repeat_hello():
print("Hello!")
# สร้าง timer ใหม่สำหรับรอบถัดไป
threading.Timer(1.0, repeat_hello).start()
# เริ่มต้น
repeat_hello()
# หยุดหลัง 5 วินาที (demo)
import time
time.sleep(5)
print("Stopping...")
ข้อควรระวัง
- Timer รันใน thread แยกต่างหาก โค้ดหลักจะดำเนินต่อไปทันที (non-blocking)
- ถ้าโปรแกรมจบก่อน timer ทำงาน timer อาจไม่รัน (daemon thread behavior)
- สำหรับงานที่ต้องการ precision สูงหรือ recurring tasks ควรใช้
schedหรือAPSchedulerแทน