I have a function constantly running in a loop checking if it should start or cancel a timer that's defined in the function's scope. Timer needs to be defined within the function as the callback is also defined in the function. I'm able to start the timer fine, but when it tries to cancel, I get an error 'local variable 'timer' referenced before assignment'.
I've tried defining the timer and its callback in the global scope (which is undesirable), and I get another error 'threads can only be started once'.
import threading import random def start(): trigger = random.randint(0,1) def do_something(): print(trigger) if trigger == 0: timer = threading.Timer(2,do_something) timer.start() else: timer.cancel() #: if trigger is 1, I want to cancel the timer threading.Timer(1,start).start() #: start() is in a loop and is constantly checking trigger's value start()
I want the same timer to be started or cancelled according to trigger's value. timer and its callback should be defined within the function.