I am trying to interupt a timer in python and cannot seem to figure out why this is not working. I am expecting "false" to be printed from the last line?
import time
import threading
def API_Post():
print("api post")
def sensor_timer():
print("running timer")
def read_sensor():
recoatCount = 0
checkInTime = 5
t = threading.Timer(checkInTime, sensor_timer)
print(t.isAlive()) #expecting false
t.start()
print(t.isAlive()) #expecting True
t.cancel()
print(t.isAlive()) #expecting false
thread1 = threading.Thread(target=read_sensor)
thread1.start()
Timer
is a subclass of the Thread
with simple implementation. It waits the provided time by subscribing to the event finished
. You need to use join on timer to guarantie that thread is actually finished:
def read_sensor():
recoatCount = 0
checkInTime = 5
t = threading.Timer(checkInTime, sensor_timer)
print(t.isAlive()) #expecting false
t.start()
print(t.isAlive()) #expecting True
t.cancel()
t.join()
print(t.isAlive()) #expecting false