Infinite "background" loop for Tornado WebSockets handler

infinite-loop, nonblocking, python-multithreading, tornado, websocket

Solution

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

Problem

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

Original source