diff --git a/InvenTree/InvenTree/apps.py b/InvenTree/InvenTree/apps.py index a13c5b8d31..0b5283706c 100644 --- a/InvenTree/InvenTree/apps.py +++ b/InvenTree/InvenTree/apps.py @@ -1,6 +1,12 @@ # -*- coding: utf-8 -*- from django.apps import AppConfig +import logging + +import InvenTree.tasks + + +logger = logging.getLogger(__name__) class InvenTreeConfig(AppConfig): @@ -8,5 +14,23 @@ class InvenTreeConfig(AppConfig): def ready(self): - print("Starting background tasks") - pass + self.start_background_tasks() + + def start_background_tasks(self): + + try: + from django_q.models import Schedule + except (AppRegistryNotReady): + return + + logger.info("Starting background tasks...") + + InvenTree.tasks.schedule_task( + 'InvenTree.tasks.delete_successful_tasks', + schedule_type=Schedule.WEEKLY, + ) + + InvenTree.tasks.schedule_task( + 'InvenTree.tasks.check_for_updates', + schedule_type=Schedule.DAILY + ) diff --git a/InvenTree/InvenTree/settings.py b/InvenTree/InvenTree/settings.py index 323eade258..2c96fa8706 100644 --- a/InvenTree/InvenTree/settings.py +++ b/InvenTree/InvenTree/settings.py @@ -188,13 +188,13 @@ INSTALLED_APPS = [ 'build.apps.BuildConfig', 'common.apps.CommonConfig', 'company.apps.CompanyConfig', - 'InvenTree.apps.InvenTreeConfig', 'label.apps.LabelConfig', 'order.apps.OrderConfig', 'part.apps.PartConfig', 'report.apps.ReportConfig', 'stock.apps.StockConfig', 'users.apps.UsersConfig', + 'InvenTree.apps.InvenTreeConfig', # InvenTree app runs last # Third part add-ons 'django_filters', # Extended filter functionality diff --git a/InvenTree/InvenTree/tasks.py b/InvenTree/InvenTree/tasks.py index 0ebfc5a2fd..e34c7e8c21 100644 --- a/InvenTree/InvenTree/tasks.py +++ b/InvenTree/InvenTree/tasks.py @@ -7,10 +7,35 @@ import logging from datetime import timedelta +from django.core.exceptions import AppRegistryNotReady + logger = logging.getLogger(__name__) +def schedule_task(taskname, **kwargs): + """ + Create a scheduled task. + If the task has already been scheduled, ignore! + """ + + try: + from django_q.models import Schedule + except (AppRegistryNotReady): + logger.warning("Could not start background tasks - App registry not ready") + return + + if Schedule.objects.filter(func=taskname).exists(): + logger.info(f"Scheduled task '{taskname}' already exists. (Skipping)") + else: + logger.info(f"Creating scheduled task '{taskname}'") + + Schedule.objects.create( + func=taskname, + **kwargs + ) + + def delete_successful_tasks(): """ Delete successful task logs @@ -32,8 +57,12 @@ def check_for_updates(): data = json.loads(response.text) + print("Response:") + print(data) # TODO + return data + def test(x): print(f"Running at task! {x}") \ No newline at end of file