title: How to shutdown tasks when MainProcess receives SIGTERM
body: <p>I'm on Heroku and therefore only have 10 seconds to shutdown all tasks when the <code>SIGTERM</code> signal is sent. Some of my tasks will create subprocesses that will run for minutes at a time. It is OK for these tasks to be shutdown halfway through. What is the best way to terminate the tasks and their child processes?</p>
  
  <p>My first approach, below, is to register a listener on the <code>SIGTERM</code> signal of the worker (MainProcess). From there, it'll revoke all running tasks of type <code>my_long_running_task_that_i_can_safely_end</code>. I've also considered just sending <code>app.control.broadcast('shutdown')</code> to shut down all worker processes. </p>
  
  <p>From within my tasks, I'll register a listener for the <code>SIGTERM</code> signal and gracefully shut itself down.</p>
  
  <p>Here is what I've got so far:</p>
  
  <pre><code>from celery.signals import worker_ready
  from celery import platforms
  
  worker_ready.connect(endit)
  
  old_term = None
  old_int = None
  
  def endit(**kwargs):
    global old_term
    global old_int
  
    old_term = platforms.signals[signal.SIGTERM]
    old_int = platforms.signals[signal.SIGINT]
  
    platforms.signals[signal.SIGTERM] = signal_term_handler
    platforms.signals[signal.SIGINT] = signal_term_handler
  
  def signal_term_handler(signal, frame):
    active = app.control.inspect().active()
    # ****** active == None here ---- This is not what I expect ******
  
    app.control.broadcast('shutdown')
    # ****** This did not appear to shutdown my worker processes either ******
  
    if signal == 2:
      old_int(signal, frame)
    elif signal == 15:
      old_term(signal, frame)
  </code></pre>
  
  <p>The problems I've run into is that <code>app.control.inspect().active()</code> returns <code>None</code>. <code>app.control.broadcast('shutdown')</code> does not appear to shut down the worker processes.</p>
  
  <p>Is this the best appraoch? I feel as if there are so many ways to do this and I don't want to go down the wrong path.</p>
  
  <p>Thanks</p>