title: Max execution time for function in python (flask)
body: <p>I am trying to limit the time a function is allowed to run in python (flask). It would look something like this:</p>
  
  <pre><code>def my_function:
      try:
          long_function_time()
      catch TimeOutException:
          return "Function took too long to execute"
  
  def long_function_time:
      #stuff here
  </code></pre>
  
  <p>I have initially tried using signals but been told thats not a good approach since flask runs in a threaded environment. I want the max execution time to be flexible, so that I easily can change it.</p>
  
  <p>The code I currently use (which sometimes does not work, don't know why):</p>
  
  <pre><code>class TimedOutExc(Exception):
    pass
  
  def deadline(timeout, *args):
    def decorate(f):
      def handler(signum, frame):
        signal.alarm(0)
        raise TimedOutExc()
  
      def new_f(*args):
  
        signal.signal(signal.SIGALRM, handler)
        signal.alarm(timeout)
        return f(*args)
  
      new_f.__name__ = f.__name__
      return new_f
    return decorate
  </code></pre>
  
  <p>Thanks in advance!</p>