我正在运行一个龙卷风应用程序,它具有定期回调函数,可以向每个连接发送消息。 e.g:
def broadcast():
for c in webSocketConnectionList:
c.write_message("message")
上面的代码类似于我所拥有的代码,并且每隔500秒从附加到IOLoop的定期回调中运行。我想做的是让它与ioloop异步运行。也就是说,这种方法使用无限循环不断重复自身。
所以问题是:如何将此方法异步循环到IOloop?
答案 0 :(得分:0)
我不确定你的意思,“与IOLoop异步。”你能解释一下你正在做什么吗?
如果要用无限循环替换PeriodicCallback,请执行以下操作:
from datetime import timedelta
from tornado import gen, ioloop
@gen.coroutine
def broadcast():
loop = ioloop.IOLoop.current()
while True:
print "broadcast"
for c in webSocketConnectionList:
c.write_message("message")
yield gen.Task(loop.add_timeout, timedelta(seconds=500))
if __name__ == "__main__":
broadcast()
ioloop.IOLoop.current().start()
yield
语句允许循环在broadcast
方法暂停时继续运行并处理其他事件(如HTTP请求)。