title: Python async websocket client with async timer
body: <p>I need to have a long running websocket client that receives push messages from a websocket server and I need to monitor the client's connection state: if the connection goes down, I need to find out. </p>
  
  <p>My approach is to periodically log a constant string, and trigger an alarm if ever the log message is not detected.</p>
  
  <p>My idea: 1) have a websocket client that responds to irregularly incoming messages. And 2) at the same time have loop that stops logging a message when the websocket client throws a ConnectionClosed exeption.</p>
  
  <p>I am intrigued by the new 3.5 async syntax. <a href="https://github.com/aaugustin/websockets" rel="noreferrer">This websocket</a> implementation is specifically based on the asyncio. The <a href="https://websockets.readthedocs.org/en/stable/intro.html#basic-example" rel="noreferrer">client</a> in the docs look exactly like what I need. </p>
  
  <p>However, I have no idea how to add a second coroutine that does my logging statements <strong>and</strong> somehow stops when the websocket connection throws the ConnectionClosed.</p>
  
  <p>Here is something to start the conversation but that doesn't work because the alive method blocks the event loop. What I am looking for is an elegant solution to run both methods concurrently.</p>
  
  <pre><code>#!/usr/bin/env python
  
  import asyncio
  import logging
  
  import websockets
  
  logger = logging.getLogger(__name__)
  
  is_alive = True
  
  
  async def alive():
      while is_alive:
          logger.info('alive')
          await asyncio.sleep(300)
  
  
  async def async_processing():
      async with websockets.connect('ws://localhost:8765') as websocket:
          while True:
              try:
                  message = await websocket.recv()
                  print(message)
  
              except websockets.exceptions.ConnectionClosed:
                  print('ConnectionClosed')
                  is_alive = False
                  break
  
  
  asyncio.get_event_loop().run_until_complete(alive())
  asyncio.get_event_loop().run_until_complete(async_processing())
  </code></pre>