The Python Oracle

Python timer start and reset

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle3

--

Chapters
00:00 Python Timer Start And Reset
01:09 Accepted Answer Score 6
02:05 Thank you

--

Full question
https://stackoverflow.com/questions/5656...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #multithreading #python27 #timer

#avk47



ACCEPTED ANSWER

Score 6


Based on my testing, this is because threads can only be started once, and as the timer relies on a thread, the timer can only be started once. This means that the only way to re-start the timer would be to do:

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

instead of the t = Timer part, and do

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

instead of the current re-start code.

This makes your full code:

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

Hope this helps.