How to Limit Execution Time of a Function Call

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!"

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.

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)

Limit execution time of my Method

You can do something like:
Init the start date:

LocalDateTime startDateTime = LocalDateTime.now();

And check if 1 hour has elapsed:

LocalDateTime toDateTime = LocalDateTime.now();
if (Duration.between(startDateTime, toDateTime).toHours() > 0) {
// stop the execution
}

How to limit the actual EXECUTION time of a method

The way I found to force a return from a method after a time period from the actual start of the method is a brute force approach:

    private async void SyncMethodWrapper(int id, int millis)
{
Console.WriteLine($"Start task {id}");
SemaphoreSlim ss = new SemaphoreSlim(0);
bool done = false;
System.Timers.Timer timer = null;

Stopwatch sw = null;
var task = Task.Run(() =>
{
timer = new System.Timers.Timer {Interval = millis + 100};
sw = new Stopwatch();
timer.Elapsed += (sender, args) =>
{
try
{
ss.Release(1);
Console.WriteLine($"Timeout {id}");
}
catch (Exception)
{
}
};
timer.Start();
sw.Start();
Console.WriteLine($"start timer {id}");
SyncMethod(millis, id);
done = true;
ss.Release(1);
//Console.WriteLine("done");
}
);

await ss.WaitAsync().ConfigureAwait(false);

Console.WriteLine($"ID = {id} done = {done} elapsed = {sw.Elapsed}");

ss.Dispose();
timer.Dispose();
}
}

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