Endless background loop for the Tornado WebSockets handler

I am trying to create a WebSocket server using Tornado. I would like to execute a specific command that will send a message for each IOLoop cycle.

Make it clearer; 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 a way to start auto_loopIOLoop in every loop without blocking the main thread?

I believe that for this I can use green ones, but I'm looking for a more Tornado-based solution.

thanks

+4
source share
2 answers

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_close() do handlers.discard(self).

+6

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

Source: https://habr.com/ru/post/1526566/


All Articles