title: Implementing signal handling on a sleep loop
body: <p>One of the modules in an app I'm working on is intended to be used as a long-running process on Linux, and I would like it to gracefully handle SIGTERM, SIGHUP and possibly other signals. The core part of the program is in fact a loop which periodically runs a function (which in turn wakes up another thread, but this is less important). It looks more or less like this:</p>
  
  <pre><code>while True: 
      try:
          do_something()
          sleep(60)
      except KeyboardInterrupt:
          break
  
  cleanup_and_exit()
  </code></pre>
  
  <p>What I'd like to add now is to catch SIGTERM and exit the loop, the same way a <code>KeyboardInterrupt</code> exception would. </p>
  
  <p>One thought I have is to add a flag which will be set to True by the signal handler function, and replace the sleep(60) with sleep(0.1) or whatever, with a counter that counts seconds:</p>
  
  <pre><code>_exit_flag = False
  while not _exit_flag: 
      try:
          for _ in xrange(600): 
              if _exit_flag: break
              do_something()
              sleep(0.1)
  
      except KeyboardInterrupt:
          break
  
  cleanup_and_exit()
  </code></pre>
  
  <p>and somewhere else:</p>
  
  <pre><code>def signal_handler(sig, frame): 
      _exit_flag = True
  </code></pre>
  
  <p>But I'm not sure this is the best / most efficient way to do it. </p>