title: How to run a looping function asynchronously in a Tornado.WebSocket class?
body: <p>I'm running a WebSocketHandler with Tornado, and I have a <code>while</code> loop inside the Handler. This loop blocks everything - which is very bad. How can I make the <code>tailstream()</code> function asynchronous (a.k.a. non-blocking)? (As it is now, <code>tailstream</code> blocks everything, and makes even new websocket connections impossible. I need it to run for each websocket connection.)</p>
  
  <pre><code>(...)
  class WSHandler(tornado.websocket.WebSocketHandler):
      connections = []
      filters = {}
  
  
      def allow_draft76(self):
          # for iOS 5.0 Safari
          return True
  
  
      def open(self):
          self.write_message('open')
          self.count = db.my_collection.count() - 1
          self.cursor = coll.find(tailable=True, await_data=True, skip=self.count)
          self.tailstream()
  
  
  
  
      def on_message(self, message):
          print message
  
  
  
      def on_close(self):
          self.connections.remove(self)
          self.cb.stop()
          print 'connection closed'
  
  
      @tornado.web.asynchronous
      def tailstream(self):
          while self.cursor.alive:
              try:
                  doc = self.cursor.next()
                  self.print2web(doc)
  
              except StopIteration:
                  time.sleep(1)
  
  
  
      (...)       
  </code></pre>