gpt4 book ai didi

python - Python定时器可以通过检查它是否存在来取消吗?

转载 作者:太空宇宙 更新时间:2023-11-03 20:34:10 25 4
gpt4 key购买 nike

我想检查计时器是否存在,然后通过第二次运行以下代码来停止它,但它会等待计时器停止并再次运行。

import time
import threading


def run():
print("foobar")

t = threading.Timer(3, run)

def stop_t():
time.sleep(1)
t.cancel()
print("canceled")


if t.is_alive():
t.cancel()
else:
t.start()

最佳答案

问题是,如果再次运行这段代码,就会将 t 变量重新定义为一个尚未启动的新计时器,你可以尝试这样的操作:

import time
import threading


def run():
print("foobar")

def toggle_timer(t):
if t.is_alive():
print('timer is alive, killing it')
t.cancel()
else:
t.start()
print('timer is dead, starting it')

t = threading.Timer(3, run)
toggle_timer(t)
toggle_timer(t)

输出:

timer is dead, starting it

timer is alive, killing it

关于python - Python定时器可以通过检查它是否存在来取消吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57283850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com