“Fire and forget” python async/await

后端 未结 4 1698
遥遥无期
遥遥无期 2020-11-22 14:19

Sometimes there is some non-critical asynchronous operation that needs to happen but I don\'t want to wait for it to complete. In Tornado\'s coroutine implementation you ca

4条回答
  •  粉色の甜心
    2020-11-22 14:25

    Thank you Sergey for the succint answer. Here is the decorated version of the same.

    import asyncio
    import time
    
    def fire_and_forget(f):
        def wrapped(*args, **kwargs):
            return asyncio.get_event_loop().run_in_executor(None, f, *args, *kwargs)
    
        return wrapped
    
    @fire_and_forget
    def foo():
        time.sleep(1)
        print("foo() completed")
    
    print("Hello")
    foo()
    print("I didn't wait for foo()")
    

    Produces

    >>> Hello
    >>> foo() started
    >>> I didn't wait for foo()
    >>> foo() completed
    

    Note: Check my other answer which does the same using plain threads.

提交回复
热议问题