Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a function return after 5 seconds passed in Python?

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

like image 764
alwbtc Avatar asked Aug 31 '12 14:08

alwbtc


3 Answers

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

like image 144
Eric Avatar answered Sep 30 '22 17:09

Eric


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?

like image 37
Dr. Jan-Philip Gehrcke Avatar answered Sep 30 '22 17:09

Dr. Jan-Philip Gehrcke


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
like image 28
user1544624 Avatar answered Sep 30 '22 19:09

user1544624