在旧的异步功能仍在运行时启动新的异步功能

时间:2019-10-06 13:05:17

标签: python asynchronous discord.py discord.py-rewrite

全部功能创建没有可用股票的股票列表。然后,它运行警报(循环功能),以在库存可用时提醒我。我需要同时运行所有这些 alert 循环,但是 all 会等到第一个库存可用后再开始下一个循环。

我尝试使用线程为每只股票创建线程,但是我无法等待Thread.start()

async def all(self, ctx):
   stocks = requests.get(f'https://api.torn.com/torn/? 
   selections=stocks&key={api}').json()['stocks']
   zero = []
   acronymz = []
    for items in stocks:
        if stocks[items]['available_shares'] == 0:
            zero.append(items)
            acronymz.append(stocks[items]['acronym'])

    await ctx.send(f'Zero: {zero}')

    for acronyms in zero:
        print(acronyms)
        # Thread(target=alert, args=(ctx, acronyms)).start()
        await alert(ctx, acronyms)
        # await asyncio.sleep(0.5)


async def alert(ctx, items):
    stocks = requests.get(f'https://api.torn.com/torn/?selections=stocks&key={api}').json()['stocks'][items]
    if stocks['available_shares'] == 0:
        await ctx.send(f'I am now watching {stocks["acronym"]}. I will let you know when there are shares available!')
    while stocks['available_shares'] == 0:
        stocks = requests.get(f'https://api.torn.com/torn/?selections=stocks&key={api}').json()['stocks'][items]
        print(stocks)
        await asyncio.sleep(5)
    await ctx.send(f'There are {stocks["available_shares"]} in {stocks["acronym"]}')

股票= https://pastebin.com/FhuR4d4R [“股票”]

1 个答案:

答案 0 :(得分:0)

您可以为事件循环安排任务,而无需立即await对其进行调度。这是使用asyncio.gather

的示例
await asyncio.gather(*(alert(ctx, acronyms) for acronyms in zero))