如何调用异步函数而不期望它们返回?

Dan*_*Dan 3 parallel-processing asynchronous wait python-3.x 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))
Run Code Online (Sandbox Code Playgroud)

我想处理在 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)
Run Code Online (Sandbox Code Playgroud)

Mik*_*mov 6

如果我理解正确的话,当你创建任务时你已经拥有了你想要的东西。创建的任务将在“后台”执行:您不必等待它。

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())
Run Code Online (Sandbox Code Playgroud)

结果:

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
Run Code Online (Sandbox Code Playgroud)