How to set a timer & clear a timer?

这一生的挚爱 提交于 2021-02-06 09:01:32

问题


I want to create a timer. When it times out, some actions will be taken. But, I can interrupt this timer and reset it. The pseudo code looks like below:

def timeout():
    print "time out!"
    T.cancel()  # reset timer T
    T = Timer(60, timeout)  
    T.start()

T = Timer(60, timeout)

def interrupt():
    T.cancel()  # reset timer T
    T = Timer(60, timeout)
    T.start()

if __name__ == '__main__':
    T.start()
    while True:
        if something is True:
            # interrupt

The solution I came up with is cancel the timer in function interrupt and then create a new timer. But it seems a timer is canceled and a new timer is created, which is not high performance. Any idea?


回答1:


The threading.Timer() class is likely what you're looking for:

from __future__ import print_function
from time import sleep
from random import random
from threading import Timer

def timeout():
    print("Alarm!")

t = Timer(10.0, timeout)
t.start()              # After 10 seconds, "Alarm!" will be printed

sleep(5.0)
if random() < 0.5:     # But half of the time
     t.cancel()        # We might just cancel the timer
     print('Canceling')


来源:https://stackoverflow.com/questions/24968311/how-to-set-a-timer-clear-a-timer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!