Search code examples
pythontimer

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


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.


Solution

  • 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