2

I'd like to improve a currently working situation in a more elegant way if there is one.

I need to start a set of long running concurrent tasks with some of them starting with a delay.

So far I'm using gather and made a small wrapper function that wraps the task after an asyncio.sleep

The wrapper is as follows:

async def wrapper(delay, cb, *args, **kwargs):
    await asyncio.sleep(delay)
    return cb(*args, **kwargs)

And in the main function:

loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(
    immediate_coroutine(),
    wrapper(2.0, wrapped_coroutine)
))

I've found call_later could be useful but it doesn't expect an async function as its callback.

Is there a better way of handling tasks with asyncio for such cases of start delay?

1 Answer 1

3

The last line of wrapper should contain an await: return await cb(*args, **kwargs).

Is there a better way of handling tasks with asyncio for such cases of start delay?

With the above error fixed, that is pretty much how you're supposed to do it. A possible area for improvement is that wrapper doesn't need to accept callback and arguments, it can accept a coroutine object (or any kind of awaitable, really). This is safe because coroutines don't start running when you call the coroutine function, but only as the event loop drives the resulting object.

The resulting API is somewhat simpler and closer to the ones provided by asyncio:

async def wrapper(delay, coro):
    await asyncio.sleep(delay)
    return await coro

Usage:

loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(
    immediate_coroutine(),
    wrapper(2.0, wrapped_coroutine())
))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.