改善setInterval的当前实现


问题内容

我试图弄清楚如何使setInterval在python中取消而不创建整个新类来做到这一点,我想出了办法,但是现在我想知道是否有更好的方法可以做到这一点。

下面的代码似乎工作正常,但我尚未对其进行 全面 测试。

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之间有几秒钟的时间重复调用一个函数,并且可以取消以后的调用:

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()

注意:interval无论通话多长时间,此版本都会在每次通话后等待约几秒钟func(*args)。如果节拍器状蜱期望则执行可以与被锁定timer()stopped.wait(interval)可以替换为stopped.wait(interval - timer() % interval)其中timer()定义了当前时间(秒)如(其可以是相对的),
time.time()。请参阅在Python中每x秒重复执行一个函数的最佳方法是什么?