I want to run a function for 10s then do other stuff. This is my code using Timer
from threading import Timer
import time
def timeout():
b='true'
return b
a='false'
t = Timer(10,timeout)
t.start()
while(a=='false'):
print '1'
time.sleep(1)
print '2'
I know that using Timer I can print something at the end of the timer (print b instead of return b return true after 10s). What I want to know is : can I get the value returned by timeout() inside "a" to perform my while loop correctly?
Or is there another way to do it with another function ?
Pythom time method time() returns the time as a floating point number expressed in seconds since the epoch, in UTC. Note − Even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second.
In Python, Timer is a subclass of Thread class. Calling the start() method, the timer starts. Timer objects are used to create some actions which are bounded by the time period. Using timer object create some threads that carries out some actions.
Python timer functions 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).
The return value of the function is just dropped by Timer
, as we can see in the source. A way to go around this, is to pass a mutable argument and mutate it inside the function:
def work(container):
container[0] = True
a = [False]
t = Timer(10, work, args=(a,))
t.start()
while not a[0]:
print "Waiting, a[0]={0}...".format(a[0])
time.sleep(1)
print "Done, result: {0}.".format(a[0])
Or, use global
, but that's not the way a gentleman goes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With