Break the Function After Certain Time

Break the function after certain time

I think creating a new process may be overkill. If you're on Mac or a Unix-based system, you should be able to use signal.SIGALRM to forcibly time out functions that take too long. This will work on functions that are idling for network or other issues that you absolutely can't handle by modifying your function. I have an example of using it in this answer:

Option for SSH to timeout after a short time? ClientAlive & ConnectTimeout don't seem to do what I need them to do

Editing my answer in here, though I'm not sure I'm supposed to do that:

import signal

class TimeoutException(Exception): # Custom exception class
pass

def timeout_handler(signum, frame): # Custom signal handler
raise TimeoutException

# Change the behavior of SIGALRM
signal.signal(signal.SIGALRM, timeout_handler)

for i in range(3):
# Start the timer. Once 5 seconds are over, a SIGALRM signal is sent.
signal.alarm(5)
# This try/except loop ensures that
# you'll catch TimeoutException when it's sent.
try:
A(i) # Whatever your function that might hang
except TimeoutException:
continue # continue the for loop if function A takes more than 5 second
else:
# Reset the alarm
signal.alarm(0)

This basically sets a timer for 5 seconds, then tries to execute your code. If it fails to complete before time runs out, a SIGALRM is sent, which we catch and turn into a TimeoutException. That forces you to the except block, where your program can continue.

javascript: how can I stop a function after specific time from calling it

You can use setTimout to run a function after a set amount of time. For example:

setTimeout(hidePopup, 5000); 

Will run the below function after 5 seconds (5000 milliseconds):

function hidePopup() {
// Do the opposite
}

Break function and move on after certain time has elapsed - Python

It should work indeed - except if some code block inside functionThatMightHang is itself capturing and swallowing your TimeoutException. This kind of thing will happen if there is a try/except block capturing a bare Exception in there, and just ignoring it and continuing the calculation. (That is a poor programming practice, and even listed as so in the zen of Python).

If you have access to that function source code, hunt for try/excecpt blocks and include prints to check it, and capture specific exceptions instead of bare except.

If you can't dig into that code - you can make a single shot attempt to change the base of your TimeoutException to BaseException (in place of Exception) .

In any case, your does not seem to be the best approach to the problem you have at hand - signals really don't go along well with a lot of type of codes, including multi-threaded or other event-loop based code.

Moreover, even if your handler properly raises a Python exception at the right time, if your long-running function is native code, Python will not itself handle the exception (and thus switch execution to the except block) until the native-code function returns. I ruled that out as your (sole) problem because in that case the following print-statement would not run - it would take more than 5 seconds, and them execute the except block.

Real fix

You might want to try to run your long-term function by using Python's concurrent.future module. In that way you can run your long-term function in another thread, in a more or less transparent way (or even in another process, which will take advantage of multiple cores), and specify a timeout parameter for the execution - Python's concurrent.future machinery will deal with stopping the calculation by itself.

This example works on the interactive interpreter, and raises TimeoutError (the one used by concurrent.futures, not a custom one):

from concurrent.futures import ThreadPoolExecutor
import time

def long():
time.sleep(3)

p = ThreadPoolExecutor(1)

f = p.submit(long); f.result(timeout=1)

Kill function after a given amount of time?

Well, as always, it depends.

As you probably have already verified, both these methods work. I would say it depends on your application and correct implementation (your signalling method is a bit wrong...)

Both methods can be considered "safe" if implemented correctly. It depends if your main program outside the foo function needs to do something, or can it just sit and wait for foo to either complete or timeout. The signalling method does not allow any parallel processing, as your main program will be in foo() until it either completes or times out. BUT you need then to defuse the signal. If your foo completes in one second, your main program leaves the try/except structure, and four seconds later ... kaboom ... an exception is raised and probably uncaught. Not good.

try:
foo()
signal.alarm(0)
except TimeoutException:
print ("function terminated")

solves the problem.

I would personally prefer the multiprocessing approach. It is simpler and does not require signals and exception handling that in theory can go wrong if your program execution is not where you expect it to be when a signal is raised. If it is ok for your program to wait in join(), then you are done. However, if you want to do something in the main process while you wait, you can enter a loop, track time in a variable, check if over timeout and if so, terminate the process. You would just use join with a tiny timeout to "peek" if the process is still running.

Another method, depending on your foo(), is to use threads with a class or a global variable. If your foo keeps processing commands instead of possibly waiting for a long time for a command to finish, you can add an if clause there:

def foo():
global please_exit_now
while True:
do_stuff
do_more_stuff
if foo_is_ready:
break
if please_exit_now is True:
please_exit_now = False
return
finalise_foo
return

If do_stuff and do_more_stuff complete in a reasonable amount of time, you could then process things in your main program and just set global please_exit_now as True, and your thread would eventually notice that and exit.

I would probably just go for your multiprocessing and join, though.

Hannu

Stop code after time period

Here you go:

import multiprocessing
import time

# Your foo function
def foo(n):
for i in range(10000 * n):
print "Tick"
time.sleep(1)

if __name__ == '__main__':
# Start foo as a process
p = multiprocessing.Process(target=foo, name="Foo", args=(10,))
p.start()

# Wait 10 seconds for foo
time.sleep(10)

# Terminate foo
p.terminate()

# Cleanup
p.join()

This will wait 10 seconds for foo and then kill it.

Update

Terminate the process only if it is running.

# If thread is active
if p.is_alive():
print "foo is running... let's kill it..."

# Terminate foo
p.terminate()

Update 2 : Recommended

Use join with timeout. If foo finishes before timeout, then main can continue.

# Wait a maximum of 10 seconds for foo
# Usage: join([timeout in seconds])
p.join(10)

# If thread is active
if p.is_alive():
print "foo is running... let's kill it..."

# Terminate foo
p.terminate()
p.join()

How to kill Javascript function after a certain amount of time

The two functions you created have nothing to do with each other. The fact that they have the same names is irrelevant.

setTimeout is used to schedule some work in the future. But the function you pass to setTimeout doesn't do anything at all, so it's unnecessary.

Instead, you have to keep track of when the function was called the first time and check how much time has passed every time the function is called. If enough time has passed, don't call window.scrollBy(0, 10) again to prevent re-triggering the event.

var startTime;function scrollFunction() {  if (!startTime) {    // Called for the first time    startTime = Date.now();  } else if (Date.now() - startTime > 2000) {    // Stop condition. Have 2 seconds passed?    startTime = null;    return;  }  window.scrollBy(0, 10);}
window.onscroll = scrollFunction;
<div style="height:1000px; background-color:red;"></div><div style="height:1000px; background-color:green;"></div><div style="height:1000px; background-color:blue;"></div><div style="height:1000px; background-color:black;"></div>

How to stop executinf function after certain amount of time in JavaScript

hmm, I drafted this example. So it's a function that runs every second and if it takes more than 6 seconds it will stop. So basically you can put your work load in the doSomething() function and let it work every second and stop it if it takes too long. Or you can stop it based on a value. It depends on what do you want to do with it. I used the module pattern to isolate the logic and the variables. So you can encapsulate your logic in a module like way.

(function() {
'use strict';
let timing = 0;

const interval = setInterval(doSomething, 1000);

function doSomething() {
timing++;

if (timing > 5) {
clearInterval(interval);
}

console.log('working');
}
})();

Is this something you are looking for?

Exit function after certain time in C++

You're going to need to make exponential_func cooperatively exit when it is told to do so, by passing in a time deadline.

If it's literally impossible to modify that function, then you can run it on a separate thread, and terminate the thread when the deadline is up. However, this risks leaving data that exponential_func was using (which may include global data structures such as the heap) in a corrupted state. So it is typically not good practice to do this, and I only offer it as a hypothetical idea.

So a better option in this case would be to spawn another process that accepts data via some sort of IPC, runs exponential_func, retrieves results via IPC, and can be terminated if it passes the deadline. If I were writing production-ready code, this is what I'd do.



Related Topics



Leave a reply



Submit