python - 有什么方法可以扩展 python 中的 threading.Timer

标签 python multithreading timer

对于threading.Timer对象,有没有办法在调用start方法后更新计时器时间?

例如

timer = threading.Timer(5, function)
timer.start()
#after calling start method, i want to extend the timer time before expired.

我翻阅了threading.Timer的文档,没有办法。

那么我是否必须调用cancel方法然后再次调用start方法?

最佳答案

Timer 对象确实非常简单:

def Timer(*args, **kwargs):
    return _Timer(*args, **kwargs)

class _Timer(Thread):
    """Call a function after a specified number of seconds:

    t = Timer(30.0, f, args=[], kwargs={})
    t.start()
    t.cancel() # stop the timer's action if it's still waiting
    """

    def __init__(self, interval, function, args=[], kwargs={}):
        Thread.__init__(self)
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.finished = Event()

    def cancel(self):
        """Stop the timer if it hasn't finished yet"""
        self.finished.set()

    def run(self):
        self.finished.wait(self.interval)
        if not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
        self.finished.set()

它只是等待在 threading.Event 对象上调用 wait 并超时,然后运行提供的方法,或者如果 cancel 退出则退出叫。您可以实现自己的 Timer 版本来支持延长等待时间,但默认版本肯定不支持。

关于python - 有什么方法可以扩展 python 中的 threading.Timer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25142484/

相关文章:

python - pycaffe中SGDSolver和get_solver方法有什么区别?

c# - 从不同线程读取和写入相同的内存

linux - 让线程休眠的开销太高?

c# - ThreadAbortException 是否仍然强制执行 finally (try/catch) 部分中的代码?

python - 如何访问特定键具有特定值的字典中的所有字典

python - 名称修改示例的问题

python - Django autocomplete_light 和 city_light - 无效选择

c# - 使用c#进行多线程搜索

java - 如何延迟两个方法调用之间的时间?

c++ - boost::asio::high_resolution_timer 用法示例?