Search code examples
pythonpython-asyncio

Error when trying to start an asynchronous task


In my start function I run 3 functions + print. I want my create_task to form 2 functions and execute them synchronously, which is what is happening now. At the same time I am trying to run asynchronous function say_hi() and I want it to be executed immediately at start time, without waiting for other functions to finish and without waiting for say_hi function itself to be executed. How can I run it? If I remove await, I get an error:

RuntimeWarning: coroutine 'say_hi' was never awaited say_hi()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

code:

import asyncio
from datetime import datetime

async def say_hi():
  task = asyncio.sleep(1)
  print("HI")
  await task


async def start():
  asyncio.create_task(write_file())
  await say_hi()
  asyncio.create_task(take_time(time=datetime.now()))
  print("hi")


async def main():
  tasks = [
    start(),
  ]
  await asyncio.gather(*tasks)


asyncio.run(main())

Solution

  • If I understand you correctly, you can use another asyncio.gather to execute write_file(), take_time() and say_hi() tasks concurrently:

    import asyncio
    from datetime import datetime
    
    
    async def write_file():
        await asyncio.sleep(2)
        print("write file")
    
    
    async def take_time(time):
        await asyncio.sleep(3)
        print("take time")
    
    
    async def say_hi():
        await asyncio.sleep(1)
        print("HI")
    
    
    async def start():
        t1 = asyncio.create_task(write_file())
        t2 = asyncio.create_task(say_hi())
        t3 = asyncio.create_task(take_time(time=datetime.now()))
        await asyncio.gather(t1, t2, t3)
        print("hi")
    
    
    async def main():
        tasks = [
            start(),
        ]
        await asyncio.gather(*tasks)
    
    
    asyncio.run(main())
    

    Prints:

    HI
    write file
    take time
    hi