質問

I am trying to create a WebSocket server using Tornado. What I would like to do is execute a specific command, that will dispatch a message for every cycle of the IOLoop.

To make it more clear; let's say I have the following WebSocket handler

class MyHandler(websocket.WebSocketHandler):

def auto_loop(self, *args, **kwargs):
    self.write_message('automatic message')

Is there any way to run auto_loop on every IOLoop cycle, without blocking the main thread?

I suppose that I can use greenlets for that, but I am searching for a more Tornado-native solution.

Thank you

役に立ちましたか?

解決

You shouldn't write a message on every IOLoop cycle: you'll overwhelm your system. You want to send it every few milliseconds or seconds. A coroutine will do nicely:

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

In MyHandler.open(), do handlers.add(self), and in MyHandler.on_close() do handlers.discard(self).

他のヒント

You might also be interested in PeriodicCallback

http://tornado.readthedocs.org/en/latest/ioloop.html#tornado.ioloop.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()
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top