[Python] Is it possible to implement parallel timer in python for async task?

Discussão em 'Python' iniciado por Stack, Maio 2, 2025.

  1. Stack

    Stack Membro Participativo

    I'm studying asyncio in Python. A question came up: If I want to run a task in the background (add it to the event loop queue), I use asyncio.create_task. At the same time, if that task contains a long operation, I want to switch back to the current coroutine where the task was launched, continue doing useful work in that coroutine, but pause it when the timeout I set for the task expires, handle that case, and then resume the useful work from where it left off. Is this possible to implement in Python? It seems await wait_for won’t work here (since it waits for the timeout to expire, blocking execution).

    import asyncio

    async def long_task():
    try:
    print("Long task started")
    await asyncio.sleep(10) # Simulate a long operation
    return "Long task completed"
    except asyncio.CancelledError:
    print("Long task cancelled")
    raise

    async def main():
    background_task = asyncio.create_task(long_task())

    # Do useful work
    # and catch the moment ehn timeout is expired
    # (it may be in any line of useful work)
    # after processing the event of timeout expiring, resume the useful work

    asyncio.run(main())


    I've tried to find the solution in asyncio library but nothing found

    Continue reading...

Compartilhe esta Página