Home > Enterprise >  Python run 2 async infinite loops after the first one already started
Python run 2 async infinite loops after the first one already started

Time:01-09

I want to run 2 infinite async loops that should run simultanoesly.

However though, they are not called together.

The first loop starts running immediately and when it detects something it calls the second loop and they should run independently.

Something like this:

async def test():
    while True:
        print("test")
        time.sleep(7)


async def call_test():
    loopd = asyncio.get_running_loop()
    task = loopd.create_task(test())
    await task


async def print_main():
    while True:
        print("main")
        await call_test()
        time.sleep(5)


def main():
    loop = asyncio.get_event_loop()
    loop.create_task(print_main())
    loop.run_forever()


if __name__ == '__main__':
    main()

PS: There are a lot of similar questions, but they all run 2 independent loops from the start.

CodePudding user response:

  1. You should not use time.sleep with asyncio loop in the same thread, otherwise time.sleep will block all other tasks of the asyncio loop.

  2. You need only one asyncio loop in one thread, because only one loop can do work simultaneously in the same thread.

Your code will work with the following changes:

import asyncio


async def test():
    while True:
        print("test")
        await asyncio.sleep(7)


async def print_main():
    another_task = None
    while True:
        print("main")
        if another_task is None:
            another_task = asyncio.create_task(test())
        await asyncio.sleep(5)


def main():
    loop = asyncio.get_event_loop()
    loop.create_task(print_main())
    loop.run_forever()


if __name__ == '__main__':
    main()
  • Related