如何中断线程定时器?

How to interrupt threading timer?

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

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()

TimerThread 的子类,带有简单的 implementation. It waits the provided time by subscribing to the event finished. You need to use 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