【问题标题】:How to call asynchronous functions without expecting returns from them?如何调用异步函数而不期待它们的返回?
【发布时间】:2019-05-18 14:18:54
【问题描述】:

在下面的代码中,我想调用 task1 和 task2 但不期待这些方法的返回,这可能吗?

import asyncio
async def say(something, delay):
  await asyncio.sleep(delay)
  print(something)

loop = asyncio.get_event_loop()
task1 = loop.create_task(say('hi', 1))
task2 = loop.create_task(say('hoi', 2))
loop.run_until_complete(asyncio.gather(task1, task2))

我想在一个while循环中处理一个队列中的一些东西,而不是等待,因为我不需要返回函数,例如伪代码:

import asyncio
async def say(something, delay):
  await asyncio.sleep(delay)
  print(something)

def main():
    while True:
        # search for database news
        # call say asynchronous, but I do not need any return, I just want you to do anything, independent
        time.sleep(1)

【问题讨论】:

    标签: python-3.x asynchronous parallel-processing wait python-asyncio


    【解决方案1】:

    如果我对您的理解正确,您希望在创建任务时已经拥有。创建的任务将被执行"in background":你不必等待它。

    import asyncio
    
    
    async def say(something, delay):
      await asyncio.sleep(delay)
      print(something)
    
    
    async def main():
        # run tasks without awaiting for their results
        for i in range(5):
            asyncio.create_task(say(i, i))
    
        # do something while tasks running "in background"
        while True:
            print('Do something different')
            await asyncio.sleep(1)
    
    
    asyncio.run(main())
    

    结果:

    Do something different
    0
    Do something different
    1
    2
    Do something different
    3
    Do something different
    4
    Do something different
    Do something different
    Do something different
    Do something different
    

    【讨论】:

      猜你喜欢
      • 2018-01-03
      • 2019-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-11
      • 2019-08-03
      • 2023-02-10
      • 2020-12-23
      相关资源
      最近更新 更多