我试图找出如何在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
之间做出选择吗?
type
相当于在setInterval
内部显式声明一个内部类。 - roippi