首页 > 解决方案 > 如何中断线程定时器?

问题描述

我试图在 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()

标签: pythonpython-multithreading

解决方案


TimerThread具有简单实现的子类。它通过订阅事件来等待提供的时间finished。您需要使用join on 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()
   t.join()
   print(t.isAlive()) #expecting false

推荐阅读