In the code below I'd like to call task1 and task2 but WITHOUT expecting returns from these methods, is it possible?

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))

I would like to process something from a queue that gets to the main in a while loop, without waiting, because I do not need to return the functions, for example, a pseudo code:

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 Answers

3
Mikhail Gerasimov On

If I understood you correctly, what you want you already have when you create task. Created task will be executed "in background": you don't have to await for it.

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())

Result:

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