Eleena
Eleena

Reputation: 99

Django Background Tasks Without command

I am new to Django and the django-background-tasks package.

I am facing an issue that I couldn't do/start background task unless I forcefully run the command process_tasks , that is python manage.py process_tasks. I want to do/start background task without run the process_tasks command.

i am creating rest api .So i want to run the background task automatically, with out writing the command. how it is possible. ? i found a code. thats is shown in below.. But i didt get in which file i put the code.

from django.core.management import call_command

call_command('process_tasks')

this is my task.py

@background(schedule=60)
def rfid_sync(empid):
    try:
        print("Process start")
        emp = Employee.objects.get(EmployeeId=1)
        div = Device.objects.get(DeviceId=1)
        sync = Synchronization(
            Employee=emp,
            Device=div,
            SyncType=1
        )
        sync.save()
    except Exception as ex:
        logging.getLogger("error_logger").exception(repr(ex))

i am calling the task from my views.py

def proces_add(request):
   emp=Employee.objects.get(EmployeeId=request.data.get("Emp"))
   rfid_sync(emp.EmployeeId)

Upvotes: 0

Views: 3041

Answers (1)

Jeffrey
Jeffrey

Reputation: 204

Firstly, I would like to say that I prefer to consume the tasks with the command python manage.py process_tasks running for a few reasons, of which two are worth mentioning:

  1. It is tied to django command, thus if your app has problem, it makes sense to stop process_tasks too.
  2. Following the first reason, you might want to keep the process_tasks running as long as your app is working fine. Thus, should not write another script to invoke the process_tasks.

With these being said, if you really want to avoid manually opening a terminal and call the command line, I recommend you to implemented a function using subprocess to invoke the python manage.py process_tasks before you call the background tasks.

import subprocess
import shlex

def process_tasks():
    process_tasks_cmd = "python manage.py process_tasks --duration 60"
    process_tasks_args = shlex.split(process_tasks_cmd)
    process_tasks_subprocess = subprocess.Popen(process_tasks_args)

def proces_add(request):
   emp=Employee.objects.get(EmployeeId=request.data.get("Emp"))
   process_tasks()
   rfid_sync(emp.EmployeeId)

Upvotes: 0

Related Questions