From c2762b37f93785ea6e56b74527d902b76f3deebd Mon Sep 17 00:00:00 2001 From: Minecon724 Date: Mon, 12 May 2025 17:16:48 +0200 Subject: [PATCH] Fix scheduled delete --- src/anonchat/__init__.py | 24 ++---------------------- src/anonchat/tasks.py | 23 ++++++++++++++--------- 2 files changed, 16 insertions(+), 31 deletions(-) diff --git a/src/anonchat/__init__.py b/src/anonchat/__init__.py index add1bc9..10d1bf3 100644 --- a/src/anonchat/__init__.py +++ b/src/anonchat/__init__.py @@ -11,7 +11,6 @@ from flask_session import Session import redis from werkzeug.middleware.proxy_fix import ProxyFix from argon2 import PasswordHasher -from flask_apscheduler import APScheduler # Load environment variables from .env file load_dotenv() @@ -111,8 +110,8 @@ limiter = Limiter(get_remote_address, app=app) db = SQLAlchemy(app) # Initialize scheduler -scheduler = APScheduler() -scheduler.init_app(app) +from . import tasks +tasks.setup_tasks(app) from .admin_routes import is_admin app.jinja_env.globals['is_admin'] = is_admin @@ -137,25 +136,6 @@ register_error_handlers(app) from . import routes from . import admin_routes -# Setup scheduler jobs -def setup_scheduler_jobs(): - # Import the function from tasks.py - from .tasks import check_and_delete_expired_inquiries - - # Schedule the job to run every 6 hours - scheduler.add_job( - id='check_and_delete_expired_inquiries', - func=check_and_delete_expired_inquiries, - trigger='interval', - hours=6 - ) - - # Start the scheduler - scheduler.start() - -# Start the scheduler when the app is initialized -setup_scheduler_jobs() - # Flask CLI command to run migrations @app.cli.command("run-migrations") def run_migrations_command(): diff --git a/src/anonchat/tasks.py b/src/anonchat/tasks.py index 9f69a6f..b6c6161 100644 --- a/src/anonchat/tasks.py +++ b/src/anonchat/tasks.py @@ -1,14 +1,19 @@ -from flask import current_app +from flask import Flask, current_app +from flask_apscheduler import APScheduler + from . import db from .models import Inquiry -def check_and_delete_expired_inquiries(): - """Check and delete inquiries that have been closed for more than the configured number of hours""" - # Get app context from current_app - app = current_app._get_current_object() - - with app.app_context(): - app.logger.info(f"Running scheduled task: check_and_delete_expired_inquiries") +scheduler = APScheduler() + +def setup_tasks(app: Flask): + scheduler.init_app(app) + + scheduler.start() + +@scheduler.task('interval', hours=6) +def _check_and_delete_expired_inquiries(): + with scheduler.app.app_context(): expired_inquiries = Inquiry.get_expired_inquiries() deleted_count = 0 @@ -19,4 +24,4 @@ def check_and_delete_expired_inquiries(): if deleted_count > 0: db.session.commit() - app.logger.info(f"Automatically deleted {deleted_count} expired closed inquiries") \ No newline at end of file + scheduler.app.logger.info(f"Automatically deleted {deleted_count} expired (long closed) inquiries") \ No newline at end of file