Async Python Background Task

Question:

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
   
Asked By: rustyocean

||

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.

import asyncio


class Connection:
    pass


async def _check_conn_bg(conn: Connection):
    try:
        while True:
            # do checking code
            print(f'Checking connection: {conn}')

            await asyncio.sleep(1)
    except asyncio.CancelledError:
        print('Conn check task cancelled')


def main():
    asyncio.ensure_future(_check_conn_bg(Connection()))

    asyncio.get_event_loop().run_forever()
Answered By: cipres
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.