Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

timer

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.

like image 388
Deniz Uluğ Avatar asked Dec 26 '16 14:12

Deniz Uluğ


People also ask

How do you check if a thread is alive in Python?

is_alive() method is an inbuilt method of the Thread class of the threading module in Python. It uses a Thread object, and checks whether that thread is alive or not, ie, it is still running or not. This method returns True before the run() starts until just after the run() method is executed. Parameter(s):

How do I use the thread timer in Python?

Timer is a sub class of Thread class defined in python. It is started by calling the start() function corresponding to the timer explicitly. Create a timer that will run function with arguments args and keyword arguments kwargs, after interval seconds have passed.

How do you stop a timer thread in Python?

To end or quit the timer, one must use a cancel() function. Importing the threading class is necessary for one to use the threading class. The calling thread can be suspended for seconds using the function time. sleep(secs).

What is the difference between thread and timer?

Thread is a thread, Timer is a thread whose execution is deferred for at least a specified time.


1 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
like image 83
DXM Avatar answered Oct 09 '22 15:10

DXM