diff --git a/InvenTree/InvenTree/tasks.py b/InvenTree/InvenTree/tasks.py index 1c77febf79..efe1361bd1 100644 --- a/InvenTree/InvenTree/tasks.py +++ b/InvenTree/InvenTree/tasks.py @@ -51,32 +51,17 @@ def schedule_task(taskname, **kwargs): pass -def offload_task(taskname, *args, **kwargs): - """ - Create an AsyncTask. - This is different to a 'scheduled' task, - in that it only runs once! +def offload_task(taskname, force_sync=False, *args, **kwargs): """ + First check if the task method pointed + by taskname is implemented inside this file. - try: - from django_q.tasks import AsyncTask - except (AppRegistryNotReady): - logger.warning("Could not offload task - app registry not ready") - return + Then create an AsyncTask if workers are running. + This is different to a 'scheduled' task, + in that it only runs once! - task = AsyncTask(taskname, *args, **kwargs) - - task.run() - - -def run_task(taskname): - """ - 1. Check if task is implemented - - yes: proceed - - no: return - 2. Check if worker cluster is running - - yes: add task to queue - - no: run it as blocking process + If workers are not running or force_sync flag + is set then the task is ran synchronously. """ # Get task list @@ -84,20 +69,26 @@ def run_task(taskname): # Check if task exists if taskname not in tasks: - logger.warning(f'Task "{taskname}" is not implemented') + logger.warning(f'Task "{taskname}" is not implemented in InvenTree/tasks.py') return + try: + from django_q.tasks import AsyncTask + except (AppRegistryNotReady): + logger.warning("Could not offload task - app registry not ready") + return from InvenTree.status import is_worker_running - if is_worker_running(): + if is_worker_running() and not force_sync: # Append module path taskname = 'InvenTree.tasks.' + taskname - # Running as task - offload_task(taskname) + # Running as asynchronous task + task = AsyncTask(taskname, *args, **kwargs) + task.run() else: # Retrieve local method from task name _func = eval(taskname) - # Run it as blocking process + # Run it as synchronous task _func() diff --git a/InvenTree/InvenTree/views.py b/InvenTree/InvenTree/views.py index b27b58b40d..03fee01837 100644 --- a/InvenTree/InvenTree/views.py +++ b/InvenTree/InvenTree/views.py @@ -815,13 +815,13 @@ class CurrencyRefreshView(RedirectView): On a POST request we will attempt to refresh the exchange rates """ - from InvenTree.tasks import run_task + from InvenTree.tasks import offload_task # Define associated task from InvenTree.tasks list of methods taskname = 'update_exchange_rates' # Run it - run_task(taskname) + offload_task(taskname, force_sync=True) return redirect(reverse_lazy('settings'))