diff --git a/appinfo/info.xml b/appinfo/info.xml index 2aa7913..bb819d3 100644 --- a/appinfo/info.xml +++ b/appinfo/info.xml @@ -33,5 +33,12 @@ See [the nextcloud admin docs](https://docs.nextcloud.com/server/latest/admin_ma 2.6.0 false + + + TASK_POLLING_INTERVAL + Task polling interval + The interval in which the app will poll for new tasks, in seconds (can be floating point numbers). This will only be used when running in Kubernetes or with Nextcloud below v33. This value defaults to 5 seconds. + + diff --git a/lib/main.py b/lib/main.py index c5bfd5a..ced1a64 100644 --- a/lib/main.py +++ b/lib/main.py @@ -39,9 +39,20 @@ def log(nc, level, content): } app_enabled = Event() trigger = Event() -CHECK_INTERVAL = 5 + +try: + CHECK_INTERVAL = float(os.getenv('TASK_POLLING_INTERVAL', '5')) + if CHECK_INTERVAL <= 0: + logger.warning("Invalid TASK_POLLING_INTERVAL env variable, falling back to default 5 seconds") + CHECK_INTERVAL = 5 +except (TypeError, ValueError): + logger.warning("Invalid TASK_POLLING_INTERVAL env variable, falling back to default 5 seconds") + CHECK_INTERVAL = 5 + CHECK_INTERVAL_WITH_TRIGGER = 5 * 60 CHECK_INTERVAL_ON_ERROR = 10 +SHUTDOWN_EVENT_RECEIVED = Event() +SHUTDOWN_CLEAR = Event() @asynccontextmanager async def lifespan(_app: FastAPI): @@ -56,6 +67,10 @@ async def lifespan(_app: FastAPI): app_enabled.set() start_bg_task() yield + print("\nSIGTERM received. Processing last task and stopping to fetch and process new tasks..") + SHUTDOWN_EVENT_RECEIVED.set() + trigger.set() + SHUTDOWN_CLEAR.wait() APP = FastAPI(lifespan=lifespan) @@ -80,6 +95,9 @@ def background_thread_task(): sleep(30) continue + if SHUTDOWN_EVENT_RECEIVED.is_set(): + break + current_minute = int(strftime("%M")) if current_minute % 5 == 0: # scan dir and load new models every 5 minutes @@ -136,7 +154,7 @@ def background_thread_task(): nc.providers.task_processing.report_result(task["id"], error_message=str(e)) except (NextcloudException, RequestException) as net_err: log(nc, LogLvl.INFO, f"Network error in reporting the error: {net_err}") - + SHUTDOWN_CLEAR.set() def start_bg_task(): t = Thread(target=background_thread_task, args=()) @@ -202,6 +220,5 @@ def wait_for_tasks(interval = None): CHECK_INTERVAL = CHECK_INTERVAL_WITH_TRIGGER trigger.clear() - if __name__ == "__main__": run_app("main:APP", log_level="trace")