How to check if a Threading.Timer object is currently running in python

Question:

let’s say i defined a timer like:

def printer(data):
    print data
data= "hello"
timer_obj = Timer(5,printer,args=[data])
timer_obj.start()
# some code
if( #someway to check timer object is currently ticking):
    #do something

So is there a way that if the timer object is active right now, and by active i mean not in the function phase but in waiting phase.

Thanks in advance.

Asked By: Deniz Uluğ

||

Answers:

threading.Timer is a subclass of threading.Thread, you can use is_alive() to check if your timer is currently running.

import threading
import time

def hello():
    print 'hello'

t = threading.Timer(4, hello)
t.start()
t.is_alive() #return true
time.sleep(5) #sleep for 5 sec
t.is_alive() #return false
Answered By: DXM

@DXM answer does work if you wait for the for the timer to expire. However, if you cancel the timer, is_alive will still return True when called.

Maybe this was a regression, or an intended side effect for Python 3.

In any case, the most robust approach is to use Timer.finished attribute:

import threading
import time

def hello():
    print('hello')

t = threading.Timer(4, hello)
t.start()
print(t.finished.is_set())  # prints False
print(t.is_alive())         # prints True
time.sleep(5)               # sleeps for 5 sec
print(t.finished.is_set())  # prints True
print(t.is_alive())         # prints False

t = threading.Timer(4, hello)
t.start()
print(t.finished.is_set())  # prints False
print(t.is_alive())         # prints True
t.cancel()                  # cancel timer
print(t.finished.is_set())  # prints True
print(t.is_alive())         # prints True
Answered By: GChamon
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.