【问题标题】:Is there any way to extend threading.Timer in python有什么方法可以在 python 中扩展 threading.Timer
【发布时间】:2014-08-05 15:20:05
【问题描述】:

对于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的文档,没有办法。

所以我必须调用取消方法然后再次调用启动方法吗?

【问题讨论】:

    标签: python multithreading timer


    【解决方案1】:

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

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

    【讨论】:

    • 如何访问 treading.Event 以获取 wait 方法?
    【解决方案2】:

    没有人发布任何代码示例,所以我也不妨想想。在这里,我按照上面的建议做了,定时器被取消然后重新启动。使用此解决方案首先会导致“hello world”每 5 秒打印一次,然后在重新运行时将其频率增加到每秒一次。它还打印了一些 Epoch 时间来演示并发性

    import time
    import threading
    
    def printit(runs):
      if runs == 1:
          timer = threading.Timer(5.0, printit, [runs])
          timer.start()
          runs += 1
      else:
          timer = threading.Timer(1.0, printit, [runs])
          timer.start()
    
      print("Hello, World!")
      timer.cancel()
      timer = threading.Timer(1.0, printit, [runs])
      timer.start()
    
    if __name__ == '__main__':
        runs = 1
        printit(runs)
        now = time.time()
        print('The current time is: ' + str(now))
        time.sleep(7)
        current = time.time()
        print('The current time is: ' + str(current))
    

    【讨论】:

      【解决方案3】:

      取消计时器并开始一个新的。

      【讨论】:

        猜你喜欢
        • 2020-08-09
        • 1970-01-01
        • 2014-08-12
        • 1970-01-01
        • 2010-10-28
        • 2012-05-18
        • 1970-01-01
        • 2017-05-01
        • 1970-01-01
        相关资源
        最近更新 更多