title: How to schedule and cancel tasks with asyncio
body: <p>I am writing a client-server application. While connected, client sends to the server a "heartbeat" signal, for example, every second.
  On the server-side I need a mechanism where I can add tasks (or coroutines or something else) to be executed asynchronously. Moreover, I want to cancel tasks from a client, when it stops sending that "heartbeat" signal. </p>
  
  <p>In other words, when the server starts a task it has kind of timeout or <em>ttl</em>, in example 3 seconds. When the server receives the "heartbeat" signal it resets timer for another 3 seconds until task is done or client disconnected (stops send the signal).</p>
  
  <p>Here is an <a href="https://pymotw.com/3/asyncio/index.html" rel="noreferrer">example</a> of canceling a task from <em>asyncio</em> tutorial on pymotw.com. But here the task is canceled before the event_loop started, which is not suitable for me.</p>
  
  <pre><code>import asyncio
  
  async def task_func():
      print('in task_func')
      return 'the result'
  
  
  event_loop = asyncio.get_event_loop()
  try:
      print('creating task')
      task = event_loop.create_task(task_func())
  
      print('canceling task')
      task.cancel()
  
      print('entering event loop')
      event_loop.run_until_complete(task)
      print('task: {!r}'.format(task))
  except asyncio.CancelledError:
      print('caught error from cancelled task')
  else:
      print('task result: {!r}'.format(task.result()))
  finally:
      event_loop.close()
  </code></pre>