如何在不期望异步函数返回收益的情况下调用异步函数?

时间:2019-05-18 14:18:54

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

在下面的代码中,我想调用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)

1 个答案:

答案 0 :(得分:3)

如果我对您的理解正确,那么创建任务时您已经拥有了什么。创建的任务将执行"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