fix: properly start/stop tasks (#100)

* fix: properly start/stop tasks

https://github.com/lnbits/lnbits/issues/2411
This commit is contained in:
dni ⚡ 2024-05-27 11:47:39 +02:00 committed by GitHub
parent 2ce0c98a76
commit 6289d2d36a
2 changed files with 23 additions and 31 deletions

View file

@ -1,12 +1,13 @@
import asyncio
from asyncio import Task
from typing import List
from fastapi import APIRouter
from loguru import logger
from lnbits.db import Database
from lnbits.helpers import template_renderer
from lnbits.tasks import catch_everything_and_restart
from lnbits.tasks import create_permanent_unique_task
from .nostr.nostr_client import NostrClient
db = Database("ext_nostrmarket")
@ -23,12 +24,7 @@ nostrmarket_static_files = [
def nostrmarket_renderer():
return template_renderer(["nostrmarket/templates"])
from .nostr.nostr_client import NostrClient
nostr_client = NostrClient()
scheduled_tasks: List[Task] = []
nostr_client: NostrClient = NostrClient()
from .tasks import wait_for_nostr_events, wait_for_paid_invoices
@ -36,7 +32,21 @@ from .views import * # noqa
from .views_api import * # noqa
scheduled_tasks: list[asyncio.Task] = []
async def nostrmarket_stop():
for task in scheduled_tasks:
try:
task.cancel()
except Exception as ex:
logger.warning(ex)
await nostr_client.stop()
def nostrmarket_start():
async def _subscribe_to_nostr_client():
# wait for 'nostrclient' extension to initialize
await asyncio.sleep(10)
@ -47,8 +57,7 @@ def nostrmarket_start():
await asyncio.sleep(15)
await wait_for_nostr_events(nostr_client)
loop = asyncio.get_event_loop()
task1 = loop.create_task(catch_everything_and_restart(wait_for_paid_invoices))
task2 = loop.create_task(catch_everything_and_restart(_subscribe_to_nostr_client))
task3 = loop.create_task(catch_everything_and_restart(_wait_for_nostr_events))
task1 = create_permanent_unique_task("ext_nostrmarket_paid_invoices", wait_for_paid_invoices)
task2 = create_permanent_unique_task("ext_nostrmarket_subscribe_to_nostr_client", _subscribe_to_nostr_client)
task3 = create_permanent_unique_task("ext_nostrmarket_wait_for_events", _wait_for_nostr_events)
scheduled_tasks.extend([task1, task2, task3])