Python 计时器启动和重置



我正在尝试让一个计时器功能在Python中工作(目前是Python 2.7(。

这是我到目前为止所拥有的。我正在努力解决线程问题并重置计时器。

from threading import Timer
def api_call():
    print("Call that there api")
t = Timer(10.0,api_call)

def my_callback(channel):
    if something_true:
        print('reset timer and start again')
        t.cancel()
        t.start()
        print("n timer started")
    elif something_else_true:
        t.cancel()
        print("timer canceled")
    else:
       t.cancel()
       print('cancel timer for sure')
try:
    if outside_input_that_can_happen_a_lot:
        my_callback()
finally:
    #cleanup objects

基本上,my_callback()可以非常快速地调用很多次,并且可以点击"if"、"elif"或"else"语句的任何部分。

我遇到的问题是,当something_true变量为真时,它将启动一个计时器。第一次效果很好。每次调用它之后,我都会收到一个线程错误,告诉我只有一个线程可以用于计时器。

基本上,我希望能够在第一个"if"上重置计时器,并在命中"elif"或"else"时取消。

根据我的测试,这是因为线程只能启动一次,并且由于计时器依赖于线程,因此计时器只能启动一次。这意味着重新启动计时器的唯一方法是执行以下操作:

def newTimer():
    global t
    t = Timer(10.0,api_call)
newTimer()

而不是 t = 计时器部分,然后做

t.cancel()
newTimer()
t.start()

而不是当前的重新启动代码。

这使您的完整代码:

from threading import Timer
def api_call():
    print("Call that there api")
def newTimer():
    global t
    t = Timer(10.0,api_call)
newTimer()

def my_callback(channel):
    if something_true:
        print('reset timer and start again')
        t.cancel()
        newTimer()
        t.start()
        print("n timer started")
    elif something_else_true:
        t.cancel()
        print("timer canceled")
    else:
       t.cancel()
       print('cancel timer for sure')
try:
    if outside_input_that_can_happen_a_lot:
        my_callback()
finally:
    #cleanup objects

希望这有帮助。

最新更新