说我有一个等待websocket消息的主循环并对其进行处理,我还希望无阻塞的心跳协程可以通过ping通并在出现异常时停止主循环来检查连接的运行状况。
我想知道什么是最好的方法。
这是我对这个概念的抽象实现,我不知道这是最健壮或最有效的方法。
有什么建议吗?
import asyncio
import logging
import random
logging.basicConfig(level=10, format="%(asctime)s %(threadName)s %(name)s.%(funcName)s [%(levelname)s]: %(message)s")
logger = logging.getLogger()
async def heart_beat():
logger.info('heart beat...')
await asyncio.sleep(10) # so this task will run roughly every 10s
return 10/random.randint(0, 10) # this task has 1/10 chance of failing
async def main_loop():
fut = asyncio.ensure_future(heart_beat())
while True:
if fut.done():
ret = await fut # if finished, get result, if error, which will be raised here
logger.info(f'result from heart beat {ret}...')
fut = asyncio.ensure_future(heart_beat()) # spawn another heart beat
logger.info('new message...')
await asyncio.sleep(1) # resembles await functions that gets messages from ws
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main_loop())