Search code examples
pythonasynchronoustimerpython-asyncio

Python - run an async funtion after delay and do not block other code


Here is my code:

async def outer():
    # if this while loop was not broken in 5 seconds, do something
    while True:
        # some code with breaks
    

Generally i need a non-blocking asynchronous timer.


Solution

  • def outer():
        async def loop():
             #while loop here
      
    
        task = asyncio.create_task(loop())
        done, pending = await asyncio.wait([task], return_when=asyncio.FIRST_COMPLETED, timeout=5)
        if task in done:
            # loop has completed
        else:
           # loop is incomplete
    
    

    References: