如何在Tornado.WebSocket类中异步运行循环函数?

时间:2012-09-30 19:25:33

标签: python asynchronous tornado

我正在使用Tornado运行WebSocketHandler,并且我在Handler中有一个while循环。这个循环阻止了一切 - 这是非常糟糕的。如何使tailstream()函数异步(a.k.a.非阻塞)? (就像现在一样,tailstream会阻止所有内容,甚至无法实现新的websocket连接。我需要为每个websocket连接运行它。)

(...)
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)



    (...)       

1 个答案:

答案 0 :(得分:2)

我认为while没有阻止它。但是time.sleep呢!

yield gen.Task(IOLoop.instance().add_timeout, time.time() + 5)替换为此answer

如果没有帮助 - 我们可以考虑整个解决方案的结构。

相关问题