Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions crontask/management/commands/crontask.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import importlib
import logging
import signal
import sys

from apscheduler.executors.pool import ThreadPoolExecutor
from apscheduler.triggers.interval import IntervalTrigger
from django.apps import apps
from django.core.management import BaseCommand
Expand All @@ -28,6 +30,7 @@ class Command(BaseCommand):
"""Run task scheduler for all tasks with the `cron` decorator."""

help = __doc__
LOCK_EXECUTOR_ALIAS = "lock"

def add_arguments(self, parser):
parser.add_argument(
Expand Down Expand Up @@ -73,11 +76,20 @@ def launch_scheduler(self, lock, scheduler):
self.stdout.write(self.style.SUCCESS("Starting scheduler…"))
# Periodically extend TTL of lock if needed
# https://redis-py.readthedocs.io/en/stable/lock.html#redis.lock.Lock.extend
# A dedicated executor scopes the log level to the lock job only.
scheduler.add_executor(
ThreadPoolExecutor(max_workers=1),
self.LOCK_EXECUTOR_ALIAS,
)
logging.getLogger(f"apscheduler.executors.{self.LOCK_EXECUTOR_ALIAS}").setLevel(
logging.WARNING
)
scheduler.add_job(
utils.extend_lock,
IntervalTrigger(seconds=conf.get_settings().LOCK_REFRESH_INTERVAL),
args=(lock, scheduler),
name="crontask.utils.lock.extend",
executor=self.LOCK_EXECUTOR_ALIAS,
)
try:
scheduler.start()
Expand Down
12 changes: 12 additions & 0 deletions tests/test_commands.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import io
import logging
import signal
import sys
from unittest.mock import Mock, patch
Expand Down Expand Up @@ -119,6 +120,17 @@ def test_handle(self, monkeypatch):
with io.StringIO() as stdout:
call_command("crontask", stdout=stdout)
assert "Starting scheduler…" in stdout.getvalue()
scheduler.add_executor.assert_called_once()
assert (
logging.getLogger(
f"apscheduler.executors.{crontask.Command.LOCK_EXECUTOR_ALIAS}"
).level
== logging.WARNING
)
assert (
scheduler.add_job.call_args.kwargs["executor"]
== crontask.Command.LOCK_EXECUTOR_ALIAS
)
scheduler.start.assert_called_once()

def test_handle__keyboard_interrupt(self, monkeypatch):
Expand Down
Loading