I want to write a function which will return after 5 seconds no matter what:
def myfunction():
while passed_time < 5_seconds:
do1()
do2()
do3()
.
.
return
I mean, this function run for 5 seconds only, after 5 seconds, it should end, and continue with other function:
myfunction()
otherfunction() ----> This should start 5 seconds after myfunction() is executed.
Best Regards
You can do:
def myfunction():
start = time.time()
while time.time() < start + 5:
do1()
do2()
do3()
Note that this will stop after at least 5 seconds - if do1
, do2
, and do3
each take 3 seconds, then this function will take 9 seconds.
If you want to cut off myFunction
between these calls, you can do:
def myfunction():
todo = itertools.cycle([do1, do2, do3])
start = time.time()
while time.time() < start + 5:
todo.next()()
This case would take 6s
If there is a chance that the execution time of your functions is longer than the interval between firing these functions, you'd have to start these functions in another thread or process.
Example with threading
:
import time
import sys
from threading import Thread
def f1():
print "yo!!"
time.sleep(6)
def f2():
print "boring."
time.sleep(2)
if __name__ == "__main__":
threads = []
try:
for f in [f1, f2]:
t = Thread(target=f)
t.start()
threads.append(t)
time.sleep(5)
except KeyboardInterrupt:
sys.exit(0)
finally:
[t.join() for t in threads]
I understood the question in the way that you do not necessarily need to kill/end one function after exactly 5 seconds. Your main goal is to fire up the functions with a 5 second interval. If you need to 'kill' the functions after a certain time, this won't be trivial using threads: Is there any way to kill a Thread in Python?
You can also do:
import time
start=time.time()
stuff={1:do1,2:do2,3:do3,...}
i=1
while time.time() <= start+5:
stuff[i]()
i+=1
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