繁体   English   中英

python asyncio:异步任务功能的模式

[英]python asyncio: pattern for async tasks function

我有一个需要运行多个独立任务的程序。 我需要一种方法来启动它们,然后在事件发生时停止它们

我已经定义了一个这样的基类

class InterruptibleTask:
    def __init__(self, stop_evt=None):
        self.stop_evt = stop_evt or asyncio.Event()

    async def init(self):
        pass

    async def cleanup(self):
        pass

    async def run(self):
        await self.init()
        await self.stop_evt.wait()
        await self.cleanup()

    async def stop(self):
        self.stop_evt.set()


class MyFirstTask(InterruptibleTask):
    async def do_work(self):
        while not self.stop_evt.is_set:
            print("Do Work")
            asyncio.sleep(1)

    async def init(self):
        await asyncio.create_task(self.do_work())

class MysecondTask(InterruptibleTask):
    async def do_work(self):
        while not self.stop_evt.is_set:
            print("Do 2nd Work")
            asyncio.sleep(3)

    async def init(self):
        await asyncio.create_task(self.do_work())


STOP = asyncio.Event()
tasks = [MyFirstTask(STOP), MysecondTask(STOP)]


async def run_tasks():
    await asyncio.gather(*tasks)


def stop_tasks():
    for task in tasks:
        task.stop()

try
    asyncio.run(run_tasks())
except KeyboardInterrupt:
    pass
finally:
    stop_tasks()

这是正确的方法吗? 你有什么例子吗? 如何在退出时停止所有任务和子任务?

当我有几个协程并想停止我的循环时我会怎么做:

try:
    loop.run_until_complete(main())
except KeyboardInterrupt:
    pending = asyncio.Task.all_tasks()
    for c in pending:
        asyncio.wait_for(c, timeout=5)
finally:
    loop.stop()

所以我不必对我的协程进行任何簿记,并且仍然可以确保每个协程都停止。 由于协程可能需要很长时间才能完成,因此我添加了超时,因此我不必等待数年才能关闭我的程序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM