【发布时间】:2021-10-11 06:27:07
【问题描述】:
代码:
class App:
def __init__(self):
# some of the code
...
...
xxx.add_handler(self.event_handler, event_xyz)
asyncio.create_task(self.keep_alive())
xxx.run_until_disconnected()
def keep_alive(self):
# stuff to keep connection alive
...
...
time.sleep(5) # this will block whole script
asyncio.sleep(5) # this won't work because of lack of async on _init_ and keep_alive
async def event_handler(self):
await stuff
# other functions
if __name__ == '__main__':
App()
保持连接活动的代码部分有 api 限制。所以,我需要在keep_alive() 函数中加入sleep 语句。
我知道可以完全更改代码的设计以使其正常工作,但它是一个大脚本,其他一切都运行良好。所以,最好是如果这可以工作。
只要其余代码在sleep 期间没有被阻塞,我就可以使用其他任何东西,例如线程。
【问题讨论】:
-
您的代码中是否有 ansycio 事件循环,或者这是您需要的唯一异步内容?
-
@Blckknght 用 event_handler 部分更新了代码,它是异步函数。
标签: python-3.x multithreading python-asyncio sleep