break the function after certain time

Related searches

In python, for a toy example:

for x in range(0, 3):
    # call function A(x)

I want to continue the for loop if function A takes more than 5 second by skipping it so I won't get stuck or waste time.

By doing some search, I realized subprocess or thread may help but I have no idea how to implement here. Any help will be great. Thanks

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:

https://stackoverflow.com/a/24921763/3803152

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.

EDIT: whoops, TimeoutException is a class, not a function. Thanks, abarnert!

Stop JavaScript setInterval() after a certain time, Stop our JavaScript setInterval() method from running the JavaScript code or function after a certain period of time. Here as an example, we are going to see the  There is no way to do that. There are only a few ways to run a function for a limited time without the active cooperation of the function: use parfeval() from the Parallel Processing Toolbox, and cancel() the job. use batch() from the Parallel Processing Toolbox, and cancel() the job.

JavaScripthow do I stop a script after a certain time interval , I want to stop the script from running after a time interval Here's what I got so far I think I var t=setTimeout(“call function to kill script”, 5000);. I am using Matlab to call an extrenal function. But I don't have any control on the function I am calling. I want Matlab to stop executing the function and return if it takes more than a certain time.

The comments are correct in that you should check inside. Here is a potential solution. Note that an asynchronous function (by using a thread for example) is different from this solution. This is synchronous which means it will still run in series.

import time

for x in range(0,3):
    someFunction()

def someFunction():
    start = time.time()
    while (time.time() - start < 5):
        # do your normal function

    return;

Stop program after a period of time, How do I implement a timing system to stop reading after a period of time? Time.​sleep() doesn't help in this case as it only pauses the program for a certain  It is super basic as I didn't want to spend much time on it. Much more could be added like checking if the password is a certain length, has x, y or z. So really a skeleton of a more robust password security function, but I figured I would share it anyways.

This seems like better idea (sorry, not sure of the python names of thing yet):

import signal

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

signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(3)   # Three seconds
try:
    for x in range(0, 3):
        # call function A(x)
except Exception, msg:
    print "Timeout!"
signal.alarm(0)    # reset

SetTimeout and setInterval: Delays in JavaScript, JavaScript can trigger action after an interval of time, or repeat it after an The finish function after 10 seconds will display the message "THE END" and stop the How to modify the content of a page with a time interval or a given delay. import time timeout = time.time() + 60*5 # 5 minutes from now while True: test = 0 if test == 5 or time.time() > timeout: break test = test - 1. You may also want to add a short sleep here so this loop is not hogging CPU (for example time.sleep(1) at the beginning or end of the loop body).

Maybe some one find this decorator useful, based on TheSoundDefense answer:

import time
import signal

class TimeoutException(Exception):   # Custom exception class
pass


def break_after(seconds=2):
    def timeout_handler(signum, frame):   # Custom signal handler
        raise TimeoutException
    def function(function):
        def wrapper(*args, **kwargs):
            signal.signal(signal.SIGALRM, timeout_handler)
            signal.alarm(seconds)
            try:
                res = function(*args, **kwargs)
                signal.alarm(0)      # Clear alarm
                return res
            except TimeoutException:
                print u'Oops, timeout: %s sec reached.' % seconds, function.__name__, args, kwargs
            return
        return wrapper
    return function

test:

@break_after(3)
def test(a,b,c):
    return time.sleep(10)

>>> test(1,2,3)
Oops, timeout: 3 sec reached. test (1, 2, 3) {}

Timers, The timer functions within Node.js implement a similar API as the timers API provided by the process may exit before the Immediate object's callback is invoked. is an internal construct that calls a given function after a certain period of time. setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval. These methods are not a part of JavaScript specification. But most environments have the internal scheduler and provide these methods.

import signal #Sets an handler function, you can comment it if you don't need it. signal.signal(signal.SIGALRM,handler_function) #Sets an alarm in 10 seconds #If uncaught will terminate your process. signal.alarm(10) The timeout is not very precise, but can do if you don't need extreme precision.

TIME(hour, minute, second) The TIME function syntax has the following arguments: Hour Required. A number from 0 (zero) to 32767 representing the hour. Any value greater than 23 will be divided by 24 and the remainder will be treated as the hour value. For example, TIME(27,0,0) = TIME(3,0,0) = .125 or 3:00 AM.

Is there any way to set time limit on a function?. Learn more about time limit a function . like to stop a function if it did not finish after a specific time. Is

Comments
  • Are you on Windows or Unix?
  • @TheSoundDefense mac os
  • I think having a check in the function you call to avoid getting stuck would be a smarter move, unless you are doing some heavy calculations or something has gone very wrong, you should not be stuck for 5 seconds, if you have a lot of data then maybe multiprocessing would be the way to go.
  • @Padraic Cunningham Thanks for replay. It won't work in my case since the function may experience network or CPU idling.
  • @user2372074: Do you only need this to work on Mac OS X (or at least only on Mac OS X and other reasonably modern Unix and Unix-like systems)? If so, the answer is definitely simpler. (Signals are easy in Python; Windows APCs or similar mechanisms are not…)
  • I'm pretty sure you're supposed to do that… unless it's effectively the same question and deserves exactly the same answer, in which case it's probably better to close as a dup than to copy your code over.
  • @TheSoundDefense I got an error saying: TypeError: exceptions must be old-style classes or derived from BaseException, not funtion
  • @TheSoundDefense: No, that's not right, the OP found the right solution. His change (using class) means he's defining a subclass of Exception, which is exactly what he wants. Your original code (using def) just defines a function whose parameter happens to be named Exception, and then tries to use that function as an exception class.
  • @TheSoundDefense: Yeah, I figured. Who hasn't made that kind of silly mistake? And who's ever noticed it in his own code without at least 6 hours of bashing his head against the monitor?
  • I've adapted the code for the question. Feel free to rollback.
  • thanks for your generous help. I did the second way. But I have an issue here. The func I'm calling won't update a global variable. What I'm doing here is adding some data to the global dic which didn't happen. Could you give me some idea?
  • @user2372074: In multiprocessing, you can't directly share global variables. (Or, worse, it'll sort of work—e.g., raise an exception on OS X, usually but not quite always work on other *nix, and silently update a copy instead of the original on Windows.) Go through the multiprocessing docs (just Introduction and Programming Guidelines; skip over the Reference), but the best solution is usually to use a queue to pass the objects between processes, and I'll edit an example of that into my answer.
  • Nah it'll not work , if A() takes forever the loop will never time out.