【问题标题】:Starting a new async function while the old one is still running在旧功能仍在运行时启动新的异步功能
【发布时间】:2020-02-04 00:56:10
【问题描述】:

all 函数创建一个没有可用股票的股票列表。然后它运行 alert,一个循环函数,在库存可用时提醒我。我需要同时运行所有这些 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 [“股票”]

【问题讨论】:

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


    【解决方案1】:

    您可以为事件循环安排任务,而无需立即awaiting 它们。这是一个使用asyncio.gather的示例

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

    【讨论】:

    • 这正是我所需要的!谢谢!
    猜你喜欢
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    • 2017-08-26
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    相关资源
    最近更新 更多