pythonmultithreadingmultiprocessingpython-asynciotelethon

python coroutine and while loop, how to run both


I'm trying to run two coroutines together and using async, one is teleton telegram client and one async task who get data every minute for the telegram bot. Some code:

from asyncio import Runner
from asyncio import sleep
import asyncio
async def task_coro1():
    print('First coro')
    await sleep(1)
    while True:
        #do something
        pass

async def task_coro2():
    print('Second coro')
    await sleep(1)
    while True:
        #do something
        pass

asyncio.run(task_coro1())
asyncio.run(task_coro2())

already tried with asyncio.gather, with threading

#solved

afther a while i realise taht telethon already have the loop... just added the task for the second coroutine in his event loop


Solution

  • You were almost there

    from asyncio import Runner
    from asyncio import sleep
    import asyncio
    
    async def task_coro1():
        print('First coro')
        await sleep(3)
        while True:
            await sleep(2)
            print('First coro keeps working!')
            pass
    
    async def task_coro2():
        print('Second coro')
        await sleep(2)
        while True:
            await sleep(2)
            print('Second coro keeps working!')
            pass
    
    async def main():
        await asyncio.gather(task_coro1(),task_coro2())
    
    if __name__ == "__main__":
        asyncio.run(main())
    

    By gathering the two coroutines, they'll work together using the same thread.

    Please note that while one coroutine is blocking the CPU thread the other one will not be running. This is not threading as you mentioned in the original post