python Tornado websockets how to send message every X seconds?

后端 未结 2 1450
轻奢々
轻奢々 2021-02-14 02:17

I am trying to cobble together a test which allows websockets clients to connect to a Tornado server and I want the Tornado server to send out a message to all clients every X s

相关标签:
2条回答
  • 2021-02-14 02:54

    Found that the accepted answer for this is almost exactly what I want:

    How to run functions outside websocket loop in python (tornado)

    With a slight modification, the accepted answer at the above link continually sends out ping messages. Here is the mod:

    Change:

    def test(self):
        self.write_message("scheduled!")
    

    to:

    def test(self):
        self.write_message("scheduled!")
        tornado.ioloop.IOLoop.instance().add_timeout(datetime.timedelta(seconds=5), self.test)
    
    0 讨论(0)
  • 2021-02-14 03:04

    Why don't you try write a scheduler inside it? :)

    def schedule_func():
        #DO SOMETHING#
    
    #milliseconds
    interval_ms = 15
    main_loop = tornado.ioloop.IOLoop.instance()
    sched = tornado.ioloop.PeriodicCallback(schedule_func,interval_ms, io_loop = main_loop)
    #start your period timer
    sched.start()
    #start your loop
    main_loop.start()
    
    0 讨论(0)
提交回复
热议问题