我试图找出如何在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", (), {})
的情况下执行上述操作?或者我是在决定是创建一个专用类还是继续使用type
要在调用和取消未来调用之间用
interval
秒重复调用函数,请执行以下操作:示例:
注意:这个版本在每次调用后大约等待
interval
秒,不管func(*args)
需要多长时间。如果需要节拍器一样的节拍,那么可以用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?相关问题 更多 >
编程相关推荐