【发布时间】:2018-05-26 15:04:14
【问题描述】:
这是我第一次尝试在项目中使用asyncio。我希望我的类能够初始化并运行,它的几个函数会定期“在后台”运行。我希望类的 init 在启动这些后台任务后返回,以便它可以同时继续执行同步操作。
我有什么:
class MyClass(threading.Thread):
def __init__(self, param):
self.stoprequest = threading.Event()
threading.Thread.__init__(self)
self.param = param
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop)
asyncio.ensure_future(self.periodic(), loop=self.loop)
print("Initialized")
async def periodic(self):
while True:
print("I'm here")
await asyncio.sleep(1)
def run(self):
# continue to do synchronous things
毫无疑问,这行不通。我也尝试过在 init 中使用带有run_until_complete() 的“普通”asyncio 函数,但当然 init 永远不会返回。
如何在后台定期运行属于该类的asyncio 函数,而该类的其余部分 (run()) 继续进行同步工作?
【问题讨论】:
标签: python python-asyncio