Search code examples
pythongeventpython-asyncio

What's the equivalent in asyncio of gevent.sleep(0)


If I want some code to run later I can call gevent.sleep(0) to yield from current greenlet, how to handle it in asyncio? e.g.

def spawn(f):
    def wrapper(*args, **kwargs):
        return gevent.spawn(f, *args, **kwargs)
    return wrapper


@spawn
def f(a, b):
    gevent.sleep(0)  # gevent.idle()
    print(a + b)


@spawn
def g():
    print("hello")


f(1, 3)
f(4, 5)
g()

gevent.sleep(3)

"""
Expected:
hello
4
9
"""

of this case g will run ahead of f. In asyncio is there something similar?


Solution

  • The equivalent of gevent.sleep(time) would be await asyncio.sleep(time) in asyncio. If you call await asyncio.sleep(time) would sleep/block the caller task and if there are other tasks available they will run. After the declared time passes, caller task will be available for execution.

    Example:

    import asyncio
    
    async def f():
        await asyncio.sleep(2)
        print('This is function f!')
    
    async def g():
        print("This is function g!")
    
    async def main():
        loop = asyncio.get_event_loop()
        loop.create_task(f())
        loop.create_task(g())
        await asyncio.sleep(10)
    
    asyncio.run(main())