From 435d9b557148c7d5d624fbe8146621b501c084b7 Mon Sep 17 00:00:00 2001 From: Mark Veidemanis Date: Sat, 14 Jan 2023 17:24:54 +0000 Subject: [PATCH] Implement running scheduled tasks --- core/lib/rules.py | 6 +++- core/management/commands/scheduling.py | 43 +++++++++++++++++--------- requirements.txt | 2 +- 3 files changed, 34 insertions(+), 17 deletions(-) diff --git a/core/lib/rules.py b/core/lib/rules.py index 0f750ef..c554a28 100644 --- a/core/lib/rules.py +++ b/core/lib/rules.py @@ -153,7 +153,11 @@ class NotificationRuleData(object): window_unit = window[-1] if window_unit not in SECONDS_PER_UNIT: raise RuleParseError( - f"Window unit must be one of {', '.join(SECONDS_PER_UNIT.keys())}, not '{window_unit}'", + ( + "Window unit must be one of " + f"{', '.join(SECONDS_PER_UNIT.keys())}," + f" not '{window_unit}'" + ), "window", ) window_seconds = window_number * SECONDS_PER_UNIT[window_unit] diff --git a/core/management/commands/scheduling.py b/core/management/commands/scheduling.py index 635651d..255f038 100644 --- a/core/management/commands/scheduling.py +++ b/core/management/commands/scheduling.py @@ -1,11 +1,11 @@ +import asyncio + +from apscheduler.schedulers.asyncio import AsyncIOScheduler from django.core.management.base import BaseCommand +# from core.db.storage import db +# from core.models import NotificationRule from core.util import logs -from core.models import NotificationRule -from core.db.storage import db -import aioschedule as schedule -import asyncio -from time import sleep log = logs.get_logger("scheduling") @@ -21,19 +21,32 @@ log = logs.get_logger("scheduling") INTERVALS = [60, 900, 1800, 3600, 14400, 86400] -def run_schedule(interval_seconds): + +async def job(interval_seconds): + """ + Run all schedules matching the given interval. + :param interval_seconds: The interval to run. + """ print("Running schedule", interval_seconds) - matching_rules = NotificationRule.objects.filter( - enabled=True, interval=interval_seconds - ) + # matching_rules = NotificationRule.objects.filter( + # enabled=True, interval=interval_seconds + # ) + class Command(BaseCommand): def handle(self, *args, **options): + """ + Start the scheduling process. + """ + scheduler = AsyncIOScheduler() for interval in INTERVALS: - schedule.every(interval).seconds.do(run_schedule, interval_seconds=interval) - + log.debug(f"Scheduling {interval} second job") + scheduler.add_job(job, "interval", seconds=interval, args=[interval]) + scheduler.start() loop = asyncio.get_event_loop() - - while True: - loop.run_until_complete(schedule.run_pending()) - sleep(10) \ No newline at end of file + try: + loop.run_forever() + except (KeyboardInterrupt, SystemExit): + log.info("Process terminating") + finally: + loop.close() diff --git a/requirements.txt b/requirements.txt index 69a3dad..894e9a2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -19,4 +19,4 @@ django-debug-toolbar django-debug-toolbar-template-profiler orjson msgpack -aioschedule +apscheduler