Issue
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
Solution
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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.