Shai
Shai

Reputation: 1153

Limiting the time a command can run in Python

I want to run a certain function in Python (heavy function) but I would not like it to run more than X seconds. For example, I want to run foo() and if after 20 seconds it didn't finish processing, I'd like my program to continue running. I wouldn't like my program to keep running when foo() is running, I want it to continue its run only if foo() has finished OR 20 seconds has passed (so threads won't fit here)

Any suggestions?

Upvotes: 0

Views: 122

Answers (1)

A. Wilson
A. Wilson

Reputation: 8831

The "straightforward" way is to keep an init time within the function, and at sensible times (beginning, end of loops, before/after data writes, whatever) check the current time against that. This, of course, won't necessarily stop right at twenty seconds, and won't work if your foo() is hanging at any point internally.

Otherwise, you're probably looking at this: Asynchronous method call in Python?

If your method is dealing with sockets, asyncore from the Python Standard Library could also be useful.

EDIT: To go more in-depth (from http://docs.python.org/library/multiprocessing.html#multiprocessing.Process):

import multiprocessing

#identity function, replace with your actual foo
def foo(x):
    return x

if __name__ == '__main__':
    foo_args = #some tuple containing non-kw arguments for your function
    foo_kwargs = #some dict containing kw arguments for your function

    proc = multiprocessing.Process(target=foo,args=foo_args,kwargs=foo_kwargs)

    proc.start()
    proc.join(20) #This takes a timeout argument in seconds

You can also, contrary to your assumption in the question, use threads for this. You simply make the parent thread block on the call or until timeout (with the same join call--the interfaces for threading and multiprocessing are identical).

If you need the result of the function as a return value, pipes and queues on the same page can return that.

Upvotes: 1

Related Questions