Python计时器启动和重置

tha*_*ker 5 python multithreading timer python-2.7

我正在尝试让 Timer 功能在 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
Run Code Online (Sandbox Code Playgroud)

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

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

基本上,我希望能够在第一个“if”时重置我的计时器,并在“elif”或“else”被点击时取消。

Cra*_*eak 5

根据我的测试,这是因为线程只能启动一次,而定时器依赖于线程,因此定时器只能启动一次。这意味着重新启动计时器的唯一方法是:

def newTimer():
    global t
    t = Timer(10.0,api_call)
newTimer()
Run Code Online (Sandbox Code Playgroud)

而不是 t = Timer 部分,然后执行

t.cancel()
newTimer()
t.start()
Run Code Online (Sandbox Code Playgroud)

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

这使得您的完整代码:

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
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。

  • Python 自动删除未被任何变量引用的对象(即计时器)。当 newTimer() 运行时,t 被设置为一个新的 Timer,并且旧的 Timer 被丢弃,因为它不再有任何变量引用它。这意味着它仍然只是 1 个计时器。 (2认同)