以下代码运行单个while True
循环,并为所有具有相同数据的侦听器提供服务。它的工作原理我打算工作,但我觉得它很难看。有没有更好的方法来实现这一目标?
实际上我会拖尾MongoDB oplog,解析输出并只提供感兴趣的听众。在这种情况下,listeners
将是一个dict,其键是ObjectID,例如,它是一个WebSocketHandlers数组。这听起来像个好主意吗?
class TestHandler(WebSocketHandler):
running = False
listeners = []
@gen.coroutine
def open(self):
TestHandler.listeners.append(self)
if not TestHandler.running:
TestHandler.start_stream()
def on_close(self):
TestHandler.listeners.remove(self)
@staticmethod
@gen.coroutine
def start_stream():
# this will in reality tail mongodb oplog and serve changes
# but this is nice enough to demonstrate the problem
TestHandler.running = True
i = 0
while True:
for socket in TestHandler.listeners:
socket.write_message(str(i))
i += 1
loop = IOLoop.instance()
yield gen.Task(loop.add_timeout, time.time() + 1)