title: How to run a background timer in Flask
body: <p>I'm trying to write a <a href="http://flask.pocoo.org/" rel="nofollow noreferrer">Flask</a> app that behaves correctly when running in <a href="http://kubernetes.io/" rel="nofollow noreferrer">Kubernetes</a>, especially when it comes to <a href="https://blog.risingstack.com/graceful-shutdown-node-js-kubernetes/" rel="nofollow noreferrer">graceful shutdown</a>.</p>
  
  <p>As such, I need to have the code:</p>
  
  <ul>
  <li>recieve the shutdown signal</li>
  <li>start the "shutdown timer"</li>
  <li>continue serving requests as normal until the time is "up"</li>
  <li>then shut itself down</li>
  </ul>
  
  <p>So far, what I've got is this:</p>
  
  <pre><code>from flask import Flask, abort
  import signal
  import time
  app = Flask(__name__)
  shuttingDown = False
  
  def exit_gracefully(self, signum):
      app.logger.error('Received shutdown signal. Exiting gracefully')
      global shuttingDown
      shuttingDown = True
      # TODO: wait for some time here to ensure we are not receiving any more
      # traffic
      time.sleep(20)
      exit(0)
  
  signal.signal(signal.SIGTERM, exit_gracefully)
  
  @app.route("/")
  def hello():
          return "Hello World!"
  
  @app.route("/_status/liveness")
  def liveness():
          return "I am alive"
  
  @app.route("/_status/readiness")
  def readiness():
          if not shuttingDown:
              return "I am ready"
          else:
              abort(500, 'not ready anymore')
  </code></pre>
  
  <p>The above "works" except after I send the "shutdown" signal, regular requests to "/" are not responded to, even though we are still within the shutdown "grace period" (20 seconds in the above code).</p>
  
  <p>It seems that the call to "time.sleep()" is synchronous. </p>
  
  <p>Does anyone know of any way to make this "asynchronous"? So that the app continues to service requests until the time is "up"?</p>