title: When using asyncio, how do you allow all running tasks to finish before shutting down the event loop
body: <p>I have the following code:</p>
  
  <pre><code>@asyncio.coroutine
  def do_something_periodically():
      while True:
          asyncio.async(my_expensive_operation())
          yield from asyncio.sleep(my_interval)
          if shutdown_flag_is_set:
              print("Shutting down")
              break
  </code></pre>
  
  <p>I run this function until complete. The problem occurs when shutdown is set - the function completes and any pending tasks are never run. </p>
  
  <p>This is the error:</p>
  
  <pre><code>task: &lt;Task pending coro=&lt;report() running at script.py:33&gt; wait_for=&lt;Future pending cb=[Task._wakeup()]&gt;&gt;
  </code></pre>
  
  <p>How do I schedule a shutdown correctly?</p>
  
  <p>To give some context, I'm writing a system monitor which reads from /proc/stat every 5 seconds, computes the cpu usage in that period, and then sends the result to a server. I want to keep scheduling these monitoring jobs until I receive sigterm, when I stop scheduling, wait for all current jobs to finish, and exit gracefully.</p>