我在一个线程中有一个While循环,它每10分钟判断一次Web流.

while not stop_event.is_set():
    time.sleep(600)
    response = requests.get(api_url, headers=headers, params=params)
    if response.status_code==200:
        print("UPDATED")
    else:
        print("NOT UPDATED")

但是,如果在10分钟前将not stop_event.is_set()更改为False,则While循环仍将等待10分钟并执行其余代码,然后退出

    response = requests.get(api_url, headers=headers, params=params)
    if response.status_code==200:
        print("UPDATED")
    else:
        print("NOT UPDATED")

我想马上退出,因为not stop_event.is_set()改成了False而不知道time.sleep(600)结束了

Thanks in advance

推荐答案

如果设置了内部标志,您可以使用threading.Event.wait而不是阻塞的time.sleep,它将立即返回:

while not stop_event.is_set():
    if stop_event.wait(600):
        break # or use "return" if you want the entire function to end
    response = requests.get(api_url, headers=headers, params=params)
    if response.status_code == 200:
        print("UPDATED")
    else:
        print("NOT UPDATED")

一个可重复的例子:

import time
import threading


def run_in_thread(stop_event):
    while not stop_event.is_set():
        if stop_event.wait(5):
            print(f"{time.strftime('%H:%M:%S', time.localtime())}: Stopped.")
            return
        print(f"{time.strftime('%H:%M:%S', time.localtime())}: Running.")


if __name__ == '__main__':
    stop_event = threading.Event()
    t = threading.Thread(target=run_in_thread, args=(stop_event,))
    t.start()
    time.sleep(16)
    stop_event.set()

Python-3.x相关问答推荐

使用Python请求从特定URL下载图像时出错

如何验证具有内部json字符串的json字符串?

如何在选中项目时设置QTreeView中整行的 colored颜色 ?

Python避免捕获特定异常

Pyvis和Networkx:如何根据源或目标使 node colored颜色 不同

如何绘制交叉验证的AUROC并找到最佳阈值?

将f-字符串放置在f-字符串内

PYSMB中的进度条

PySpark每毫秒使用先前的值填充数据

visual studio代码窗口中未激活虚拟环境11

提取图像中的背景并保存

如何在 20 秒后重复使用 Pillow 在现有图像上创建新图像?

Einsum 对于张量乘法很慢

具有 2 个输入的 python 3 map/lambda 方法

Python图例属性错误

迭代dict值

如果一个失败,如何取消收集中的所有剩余任务?

是否可以在每个路由的基础上限制 Flask POST 数据大小?

如何在 QGraphicsView 中启用平移和zoom

使用 python 3.0 的 Numpy