Async Python Background Task

Viewed 34

I have a sync method that has a connection updater that checks if a connection is still open, that runs in a background thread. This works as expected and continously

How would the same thing be possible in asyncio ? Would asyncio.ensure_future would be the way to do this or is there another pythonic way to accomplish the same?

def main():
    _check_conn = threading.Thread(target=_check_conn_bg)
    _check_conn.daemon = True
    _check_conn.start()

def _check_conn_bg():
    while True:
        #do checking code
   
1 Answers

Use asyncio.ensure_future(). In your coroutine make sure your code won't block the loop (otherwise use loop.run_in_executor()) It's also good to catch asyncio.CancelledError exceptions.

Related