cancel all long-running tasks (#1793)

* add centralized task management

in order to properly cleanup all long-running tasks we have to keep a list of them

* use new task management functions

* unify shutdown events

* vlads suggestions

rename variable for create_task
wrap cancel() with try/catch

fixup

* rename func to coro

---------

Co-authored-by: dni  <office@dnilabs.com>
This commit is contained in:
jackstar12
2023-08-18 10:25:33 +01:00
committed by GitHub
co-authored by dni ⚡
parent 65db43ace4
commit 1fd4d9d514
3 changed files with 46 additions and 52 deletions
+21 -1
View File
@@ -3,7 +3,7 @@ import time
import traceback
import uuid
from http import HTTPStatus
from typing import Dict, Optional
from typing import Dict, List, Optional
from fastapi.exceptions import HTTPException
from loguru import logger
@@ -19,6 +19,26 @@ from lnbits.wallets import get_wallet_class
from .core import db
tasks: List[asyncio.Task] = []
def create_task(coro):
task = asyncio.create_task(coro)
tasks.append(task)
return task
def create_permanent_task(func):
return create_task(catch_everything_and_restart(func))
def cancel_all_tasks():
for task in tasks:
try:
task.cancel()
except Exception as exc:
logger.warning(f"error while cancelling task: {str(exc)}")
async def catch_everything_and_restart(func):
try: