“无限”;背景“;Tornado WebSockets处理程序的循环

“无限”;背景“;Tornado WebSockets处理程序的循环,websocket,tornado,infinite-loop,nonblocking,python-multithreading,Websocket,Tornado,Infinite Loop,Nonblocking,Python Multithreading,我正在尝试使用Tornado创建WebSocket服务器。我想做的是执行一个特定的命令,它将为IOLoop的每个周期发送一条消息 使之更清楚;假设我有以下WebSocket处理程序 class MyHandler(websocket.WebSocketHandler): def auto_loop(self, *args, **kwargs): self.write_message('automatic message') 有没有办法在每个IOLoop循环中运行auto_loop,而

我正在尝试使用Tornado创建WebSocket服务器。我想做的是执行一个特定的命令,它将为IOLoop的每个周期发送一条消息

使之更清楚;假设我有以下WebSocket处理程序

class MyHandler(websocket.WebSocketHandler):

def auto_loop(self, *args, **kwargs):
    self.write_message('automatic message')
有没有办法在每个IOLoop循环中运行
auto_loop
,而不阻塞主线程

我想我可以使用greenlets,但我正在寻找一个更适合龙卷风的本地解决方案


谢谢你

你不应该在每个IOLoop周期都写一条消息:你会让你的系统崩溃的。您希望每隔几毫秒或几秒钟发送一次。协同程序将很好:

import datetime

from tornado.ioloop import IOLoop
from tornado import gen

handlers = set()


@gen.coroutine
def auto_loop():
    while True:
        for handler in handlers:
            handler.write_message('automatic message')

        yield gen.Task(
            IOLoop.current().add_timeout,
            datetime.timedelta(milliseconds=500))

if __name__ == '__main__':
    # ... application setup ...

    # Start looping.
    auto_loop()
    IOLoop.current().start()

在MyHandler.open()中,do
handlers.add(self)
,在MyHandler.on\u close()中,do
handlers.discard(self)

,您可能还对PeriodicCallback感兴趣

def callback(self):

    self.write_message("Hi there!")

def open(self):
    self.write_message("Connected.")
    self.pCallback = PeriodicCallback(self.callback,
                                      callback_time=250)
    self.pCallback.start()