简体   繁体   English

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

[英]python asyncio: pattern for async tasks function

I have a program that needs to run multiple independent tasks.我有一个需要运行多个独立任务的程序。 I need a way to start them and then stop them when an event occur我需要一种方法来启动它们,然后在事件发生时停止它们

I've defined a base class like this我已经定义了一个这样的基类

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()

It this the right approach?这是正确的方法吗? Do you have any example?你有什么例子吗? How can I stop all taks and subtask on exit?如何在退出时停止所有任务和子任务?

What I do when I have several coroutines and want to stop my loop:当我有几个协程并想停止我的循环时我会怎么做:

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()

So I don't have to have any bookkeeping of my coroutines and can still make sure that every coroutine is stopped.所以我不必对我的协程进行任何簿记,并且仍然可以确保每个协程都停止。 And since there can be coroutines that can take quite a long time to finish I add a timeout, so I don't have to wait for years for my programm to shut down.由于协程可能需要很长时间才能完成,因此我添加了超时,因此我不必等待数年才能关闭我的程序。

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

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