有没有办法在python中扩展threading.Timer

时间:2014-08-05 15:20:06

标签: 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.

当我查看线程文档时。定时器,没有办法。

所以我必须调用cancel方法再调用start方法吗?

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

没有人发布任何代码示例,所以想我也可以。在这里,我按照上面的建议进行了操作,取消了计时器然后重新启动。使用此解决方案首先会导致“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))

答案 2 :(得分:0)

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