如何中断线程计时器?

2024-09-24 02:27:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: importfalsereadtimedefsensorstart计时器
1条回答
网友
1楼 · 发布于 2024-09-24 02:27:51

Timer是带有简单implementationThread的一个子类。它通过订阅事件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

相关问题 更多 >