改进 setInterval 的当前实现 [英] Improve current implementation of a setInterval

查看:44
本文介绍了改进 setInterval 的当前实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was trying to figure out how to make a setInterval that cancels in python without making an entire new class to do that, I figured out how but now I'm wondering if there is a better way to do it.

下面的代码似乎工作正常,但我还没有彻底测试它.

The code below seems to work fine, but I have not thoroughly tested it.

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

Is there a way to do the above without making a dedicated class that inherits from threading.Thread or using the type("setInterval", (), {}) ? Or am I stuck in deciding between making a dedicated class or continue to use type

推荐答案

在调用之间以 interval 秒重复调用函数并能够取消以后的调用:

To call a function repeatedly with interval seconds between the calls and the ability to cancel future calls:

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

注意:无论func(*args) 花费多长时间,此版本都会在每次调用后等待interval 秒左右.如果需要类似节拍器的滴答声,则可以使用 timer() 锁定执行:stopped.wait(interval) 可以替换为 stopped.wait(interval - timer() % interval) 其中 timer() 以秒为单位定义当前时间(可能是相对的),例如 time.time().请参阅在 Python 中每 x 秒重复执行一个函数的最佳方法是什么?

Note: this version waits around interval seconds after each call no matter how long func(*args) takes. If metronome-like ticks are desired then the execution could be locked with a timer(): stopped.wait(interval) could be replaced with stopped.wait(interval - timer() % interval) where timer() defines the current time (it may be relative) in seconds e.g., time.time(). See What is the best way to repeatedly execute a function every x seconds in Python?

这篇关于改进 setInterval 的当前实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆