“Fire and forget” python async/await

后端 未结 4 1761
遥遥无期
遥遥无期 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:39

    For some reason if you are unable to use asyncio then here is the implementation using plain threads. Check my other answers and Sergey's answer too.

    import threading
    
    def fire_and_forget(f):
        def wrapped():
            threading.Thread(target=f).start()
    
        return wrapped
    
    @fire_and_forget
    def foo():
        time.sleep(1)
        print("foo() completed")
    
    print("Hello")
    foo()
    print("I didn't wait for foo()")
    

提交回复
热议问题