gpt4 book ai didi

python - 改进 setInterval 的当前实现

转载 作者:太空狗 更新时间:2023-10-29 19:35:55 25 4
gpt4 key购买 nike

我试图弄清楚如何在 python 中创建一个取消的 setInterval 而无需创建一个全新的类来执行此操作,我想出了如何做,但现在我想知道是否有更好的方法来做到这一点。

下面的代码似乎工作正常,但我还没有彻底测试它。

import threading
def setInterval(func, sec):
def inner():
while function.isAlive():
func()
time.sleep(sec)
function = type("setInterval", (), {}) # not really a function I guess
function.isAlive = lambda: function.vars["isAlive"]
function.vars = {"isAlive": True}
function.cancel = lambda: function.vars.update({"isAlive": False})
thread = threading.Timer(sec, inner)
thread.setDaemon(True)
thread.start()
return function
interval = setInterval(lambda: print("Hello, World"), 60) # will print Hello, World every 60 seconds
# 3 minutes later
interval.cancel() # it will stop printing Hello, World

有没有办法在不创建继承自 threading.Thread 的专用类或使用 type("setInterval", (), {}) 的情况下执行上述操作> ?还是我一直在决定是制作专用类(class)还是继续使用 type

最佳答案

interval 秒重复调用一个函数,并能够取消 future 的调用:

from threading import Event, Thread

def call_repeatedly(interval, func, *args):
stopped = Event()
def loop():
while not stopped.wait(interval): # the first call is in `interval` secs
func(*args)
Thread(target=loop).start()
return stopped.set

例子:

cancel_future_calls = call_repeatedly(60, print, "Hello, World")
# ...
cancel_future_calls()

注意:无论 func(*args) 花费多长时间,此版本在每次调用后等待大约 interval 秒。如果需要类似节拍器的滴答声,则可以使用 timer() 锁定执行:stopped.wait(interval) 可以替换为 stopped.wait( interval - timer() % interval) 其中 timer() 以秒为单位定义当前时间(它可能是相对的),例如 time.time()。参见 What is the best way to repeatedly execute a function every x seconds in Python?

关于python - 改进 setInterval 的当前实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22498038/

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