如何设置计时器 &清除计时器? [英] How to set a timer & clear a timer?

查看:69
本文介绍了如何设置计时器 &清除计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个计时器.当它超时时,将采取一些行动.但是,我可以中断这个计时器并重置它.伪代码如下所示:

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?

推荐答案

threading.Timer() 类可能是您要找的:

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

这篇关于如何设置计时器 &amp;清除计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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