改进setInterval python的当前实现

use*_*209 9 python python-3.x

我试图弄清楚如何制作一个在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 
Run Code Online (Sandbox Code Playgroud)

有没有办法在不创建继承threading.Thread或使用的专用类的情况下执行上述操作type("setInterval", (), {})?或者我决定在专门课程之间决定还是继续使用type

jfs*_*jfs 20

通过呼叫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
Run Code Online (Sandbox Code Playgroud)

例:

cancel_future_calls = call_repeatedly(60, print, "Hello, World")
# ...
cancel_future_calls() 
Run Code Online (Sandbox Code Playgroud)

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