改进setInterval python的当前实现

2024-06-10 14:04:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找出如何在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


Tags: 方法lambdahelloworlddeftypefunctionsec
1条回答
网友
1楼 · 发布于 2024-06-10 14:04:00

要在调用和取消未来调用之间用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()。见What is the best way to repeatedly execute a function every x seconds in Python?

相关问题 更多 >