如何中断线程计时器?



我正在尝试在python中中断一个计时器,但似乎无法弄清楚为什么这不起作用。我希望从最后一行打印"假"?

import time
import threading
def API_Post():
print("api post")
def sensor_timer():
print("running timer")
def read_sensor():
recoatCount = 0
checkInTime = 5
t = threading.Timer(checkInTime, sensor_timer)
print(t.isAlive()) #expecting false
t.start()
print(t.isAlive()) #expecting True
t.cancel()
print(t.isAlive()) #expecting false

thread1 = threading.Thread(target=read_sensor)
thread1.start()

Timer是实现简单的Thread子类。它通过订阅事件finished来等待提供的时间。您需要在计时器上使用 join 来保证线程实际上已完成:

def read_sensor():
recoatCount = 0
checkInTime = 5
t = threading.Timer(checkInTime, sensor_timer)
print(t.isAlive()) #expecting false
t.start()
print(t.isAlive()) #expecting True
t.cancel()
t.join()
print(t.isAlive()) #expecting false

最新更新