python - 如何中断线程定时器?
问题描述
我试图在 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 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
推荐阅读
- c# - AWS .NET SDK、AliasTarget 记录集问题
- react-select - 如何自定义 React-select 库的下拉列表比文档中给出的更多
- apache-spark - Spark Structured Streaming 链接聚合
- c# - 任何人都可以改进这个“IP 地址列表”正则表达式吗?
- javascript - 如何让一些 div 元素像滑块一样左右移动
- javascript - 如何在提交之前连接表单数组输入?
- css - 我想隐藏小型设备的溢出。我该怎么做?
- c# - 当某个类型的详细 url 地址时重定向到主页
- ms-access - 连续形式(组合框)在被勾选后不会立即更新值?
- ios - 如何通过单击具有 UITableViewCell 类的 .xib 文件中的按钮来传输 UIViewController?