Allow system jobs to be registered

A new registry key allows background system jobs to be registered and
automatically scheduled when rqworker starts.
This commit is contained in:
Alexander Haase 2024-10-07 14:15:39 +02:00 committed by Jeremy Stretch
parent 892c54f6b5
commit 1f103eddac
3 changed files with 26 additions and 0 deletions

View File

@ -1,7 +1,10 @@
import logging
from django.core.management.base import CommandError
from django_rq.management.commands.rqworker import Command as _Command
from netbox.registry import registry
DEFAULT_QUEUES = ('high', 'default', 'low')
@ -14,6 +17,16 @@ class Command(_Command):
of only the 'default' queue).
"""
def handle(self, *args, **options):
# Setup system jobs.
for job in registry['system_jobs'].values():
if getattr(job.Meta, 'enabled', True):
try:
logger.debug(f"Scheduling system job {job.name}")
job.enqueue_once(interval=getattr(job.Meta, 'interval'))
except AttributeError as e:
raise CommandError(f"Job {job.name} is missing required attribute in Meta: {e.name}")
# Run the worker with scheduler functionality
options['with_scheduler'] = True

View File

@ -30,6 +30,7 @@ registry = Registry({
'models': collections.defaultdict(set),
'plugins': dict(),
'search': dict(),
'system_jobs': dict(),
'tables': collections.defaultdict(dict),
'views': collections.defaultdict(dict),
'widgets': dict(),

View File

@ -3,6 +3,7 @@ from netbox.registry import registry
__all__ = (
'get_data_backend_choices',
'register_data_backend',
'register_system_job',
)
@ -24,3 +25,14 @@ def register_data_backend():
return cls
return _wrapper
def register_system_job():
"""
Decorator for registering a `JobRunner` class as system background job.
"""
def _wrapper(cls):
registry['system_jobs'][cls.name] = cls
return cls
return _wrapper