[Python] How to call asyncio.create_task() within asyncio.create_task()?

Discussão em 'Python' iniciado por Stack, Outubro 2, 2024.

  1. Stack

    Stack Membro Participativo

    I have been attempting to run 10 different looping tasks simultaneously with asyncio. All 10 tasks call "asyncio.create_task()" within their loops. I can't use "asyncio.run()" on all of them because this functions blocks the thread its called on until the task is done. So I thought that I could simply circumvent this by calling a function with "asyncio.run()" and then inside that function call my 10 looping functions through "asyncio.create_task()". The 10 looping functions are indeed called, but they themselves cannot use "asyncio.create_task()". Any suggestions on how to fix this issue?

    This is a based code I have written to demonstrate my issue:

    async def task2():
    print("Task 2 was called")

    async def task1():
    print("Task 1 was called")
    asyncio.create_task(task2())

    async def main():
    print("Main was called")
    asyncio.create_task(task1())

    asyncio.run(main())


    It prints:

    Main was called
    Task 1 was called


    Any ideas or suggestions would be appreciated :D

    Continue reading...

Compartilhe esta Página