How to Limit the Amount of Time a Function Can Run for (Add a Timeout)

How to limit the amount of time a function can run for (add a timeout)?

On POSIX you have a simple and clean solution available in signal module.

import signal
import time

class Timeout(Exception):
pass

def handler(sig, frame):
raise Timeout

signal.signal(signal.SIGALRM, handler) # register interest in SIGALRM events

signal.alarm(2) # timeout in 2 seconds
try:
time.sleep(60)
except Timeout:
print('took too long')

Caveats:

  • Does not work on all platforms, e.g. Windows.
  • Does not work in threaded applications, only the main thread.

For other readers where the caveats above are a deal breaker, you will need a more heavyweight approach. The best option is usually to run the code in a separate process (or possibly a thread), and terminate that process if it takes too long. See multiprocessing module for example.

How to limit execution time of a function call?

I'm not sure how cross-platform this might be, but using signals and alarm might be a good way of looking at this. With a little work you could make this completely generic as well and usable in any situation.

http://docs.python.org/library/signal.html

So your code is going to look something like this.

import signal

def signal_handler(signum, frame):
raise Exception("Timed out!")

signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(10) # Ten seconds
try:
long_function_call()
except Exception, msg:
print "Timed out!"

Set Time Limit for running a function Python

You can use the threading module.

The following code is an example of a Thread with a timeout:

from threading import Thread

p = Thread(target = myFunc, args = [myArg1, myArg2])
p.start()
p.join(timeout = 2)

You could add something like the following to your code, as a check to keep looping until the function should properly end:

shouldFinish = False
def myFunc(myArg1, myArg2):
...
if finishedProperly:
shouldFinish = True

while shouldFinish == False:
p = Thread(target = myFunc, args = [myArg1, myArg2])
p.start()
p.join(timeout = 2)

Timeout on a function call

You may use the signal package if you are running on UNIX:

In [1]: import signal

# Register an handler for the timeout
In [2]: def handler(signum, frame):
...: print("Forever is over!")
...: raise Exception("end of time")
...:

# This function *may* run for an indetermined time...
In [3]: def loop_forever():
...: import time
...: while 1:
...: print("sec")
...: time.sleep(1)
...:
...:

# Register the signal function handler
In [4]: signal.signal(signal.SIGALRM, handler)
Out[4]: 0

# Define a timeout for your function
In [5]: signal.alarm(10)
Out[5]: 0

In [6]: try:
...: loop_forever()
...: except Exception, exc:
...: print(exc)
....:
sec
sec
sec
sec
sec
sec
sec
sec
Forever is over!
end of time

# Cancel the timer if the function returned before timeout
# (ok, mine won't but yours maybe will :)
In [7]: signal.alarm(0)
Out[7]: 0

10 seconds after the call signal.alarm(10), the handler is called. This raises an exception that you can intercept from the regular Python code.

This module doesn't play well with threads (but then, who does?)

Note that since we raise an exception when timeout happens, it may end up caught and ignored inside the function, for example of one such function:

def loop_forever():
while 1:
print('sec')
try:
time.sleep(10)
except:
continue

How to set a time limit to run asynchronous function in node.js?

Promises are ideal for this kind of behavior you could have something like:

new Promise(function(resolve, reject){
asyncFn(param, function(err, result){
if(error){
return reject(error);
}
return resolve(result)
});

setTimeout(function(){reject('timeout')},10000)
}).then(doSomething);

this is using the basic ES6 Promise implementation. however if you want to include something like bluebird you can find more powerful tools like promisification of functions or entire modules and promise timeouts.

http://bluebirdjs.com/docs/api/timeout.html

this in my opinion would be the preferred approach.
Hope this helps

Limit execution time of an function or command PHP

set_time_limit() does run globally, but it can be reset locally.

Set the number of seconds a script is allowed to run. If this is reached,
the script returns a fatal error. The default limit is 30 seconds or, if it
exists, the max_execution_time value defined in the php.ini.

When called, set_time_limit() restarts the timeout counter from zero. In
other words, if the timeout is the default 30 seconds, and 25 seconds
into script execution a call such as set_time_limit(20) is made, the script
will run for a total of 45 seconds before timing out.

I've not tested it, but you may be able to set it locally, resetting when you leave the

<?php
set_time_limit(0); // global setting

function doStuff()
{
set_time_limit(10); // limit this function
// stuff
set_time_limit(10); // give ourselves another 10 seconds if we want
// stuff
set_time_limit(0); // the rest of the file can run forever
}

// ....
sleep(900);
// ....
doStuff(); // only has 10 secs to run
// ....
sleep(900);
// ....

set_time_limit() ... Any time spent on activity that happens outside the execution of the script such as system calls using system(), stream operations, database queries, etc. is not included when determining the maximum time that the script has been running. This is not true on Windows where the measured time is real.



Related Topics



Leave a reply



Submit