From 8f35788e1a84da6a58d8ed01ad20f5d15b8b6bb1 Mon Sep 17 00:00:00 2001 From: padreug Date: Sun, 2 Nov 2025 01:41:34 +0100 Subject: [PATCH] Adds task cleanup on extension shutdown Implements a mechanism to cancel pending background tasks when the extension is stopped. This ensures proper cleanup and prevents potential issues with lingering tasks. --- __init__.py | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/__init__.py b/__init__.py index dc64349..014ffec 100644 --- a/__init__.py +++ b/__init__.py @@ -19,11 +19,24 @@ castle_static_files = [ } ] +scheduled_tasks: list[asyncio.Task] = [] + + +def castle_stop(): + """Clean up background tasks on extension shutdown""" + for task in scheduled_tasks: + try: + task.cancel() + except Exception as ex: + logger.warning(ex) + def castle_start(): """Initialize Castle extension background tasks""" - logger.info("Starting Castle accounting extension background tasks") - asyncio.create_task(wait_for_paid_invoices()) + from lnbits.tasks import create_permanent_unique_task + + task = create_permanent_unique_task("ext_castle", wait_for_paid_invoices) + scheduled_tasks.append(task) -__all__ = ["castle_ext", "castle_static_files", "db", "castle_start"] +__all__ = ["castle_ext", "castle_static_files", "db", "castle_start", "castle_stop"]