如何在python中多处理异步/等待函数?

时间:2021-01-06 06:22:43

标签: python python-3.x async-await python-asyncio python-multiprocessing

我需要每 60 秒为我的所有汽车运行一次事件。我对下面代码的问题是 while 循环直到超时 (60) 才结束,因此只有汽车中的第一辆车运行。

class RunCars(BaseEvent):

    def __init__(self):
        interval_seconds = 60  # Set the interval for this event
        super().__init__(interval_seconds)

    # run() method will be called once every {interval_seconds} minutes
    async def run(self, client, cars):
        for car in cars:        
            channel = get_channel(client, "general")
            await client.send_message(channel, 'Running this '+str(car))
            await msg.add_reaction(str(get_emoji(':smiley:'))) 
            
            reaction = None
            while True:
                if str(reaction) == str(get_emoji(':smiley:'))
                    await client.send_message(channel, 'Finished with this '+str(car))
                try:
                    reaction, user = await client.wait_for('reaction_add', timeout=60, check=check)
                except:
                    break

我尝试将代码更改为多线程进程,但在函数内部的 async/await 和酸洗函数本身时遇到问题。

如果您有任何关于如何解决此问题的建议,我将不胜感激。

1 个答案:

答案 0 :(得分:1)

asyncio 模块允许您使用 async 方法同时执行多个 gather 方法。我认为您可以通过定义一个运行单个汽车的方法来实现您想要的行为,然后将您的 for 循环替换为对 gather 的调用,这将执行多个 run_one 协程(方法)同时:

import asyncio

class RunCars(BaseEvent):

    def __init__(self):
        interval_seconds = 60  # Set the interval for this event
        super().__init__(interval_seconds)


    async def run(self, client, cars):
        coroutines = [self.run_one(client, car) for car in cars]
        asyncio.gather(*coroutines)

    async def run_one(self, client, car):
        channel = get_channel(client, "general")
        await client.send_message(channel, 'Running this '+str(car))
        await msg.add_reaction(str(get_emoji(':smiley:'))) 
          
        reaction = None
        while True:
            if str(reaction) == str(get_emoji(':smiley:'))
                await client.send_message(channel, 'Finished with this '+str(car))
            try:
                reaction, user = await client.wait_for('reaction_add', timeout=60, check=check)
            except:
                break

通常,在编写异步代码时,您应该尝试用 async 语句替换对 for 方法的顺序调用 - 基本上是调用 async 方法的 gather 循环所以它们是并发执行的。