improve exit logic

This commit is contained in:
dmunozv04
2024-12-15 02:08:07 +01:00
parent d9ab2cd070
commit dcf53dcca9

View File

@@ -131,7 +131,6 @@ class DeviceListener:
await asyncio.create_task(self.api_helper.mark_viewed_segments(uuids)) await asyncio.create_task(self.api_helper.mark_viewed_segments(uuids))
await asyncio.create_task(self.lounge_controller.seek_to(position)) await asyncio.create_task(self.lounge_controller.seek_to(position))
# Stops the connection to the device
async def cancel(self): async def cancel(self):
self.cancelled = True self.cancelled = True
try: try:
@@ -140,10 +139,14 @@ class DeviceListener:
pass pass
async def finish(devices): async def finish(devices, web_session, tcp_connector):
for i in devices: for device in devices:
await i.cancel() await device.cancel()
await web_session.close()
await tcp_connector.close()
def handle_signal(signum, frame):
raise KeyboardInterrupt()
def main(config, debug): def main(config, debug):
loop = asyncio.get_event_loop_policy().get_event_loop() loop = asyncio.get_event_loop_policy().get_event_loop()
@@ -160,11 +163,15 @@ def main(config, debug):
devices.append(device) devices.append(device)
tasks.append(loop.create_task(device.loop())) tasks.append(loop.create_task(device.loop()))
tasks.append(loop.create_task(device.refresh_auth_loop())) tasks.append(loop.create_task(device.refresh_auth_loop()))
signal(SIGINT, lambda s, f: loop.stop()) signal(SIGTERM, handle_signal)
signal(SIGTERM, lambda s, f: loop.stop()) signal(SIGINT, handle_signal)
try:
loop.run_forever() loop.run_forever()
except KeyboardInterrupt:
print("Cancelling tasks and exiting...") print("Cancelling tasks and exiting...")
loop.run_until_complete(finish(devices)) for task in tasks:
loop.run_until_complete(web_session.close()) task.cancel()
loop.run_until_complete(tcp_connector.close()) loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))
loop.run_until_complete(finish(devices, web_session, tcp_connector))
finally:
loop.close() loop.close()