Django extension job run daily

608 Views Asked by At

I'm trying to implement django extension management job. I would like to know how could I fire the job inside django in order to run the code daily and specify exact time like 4:00 am in django extension management job. so far code given below:

from django_extensions.management.jobs import DailyJob

class Job(DailyJob):
    help = "Send notification On Instruction Instances"

      
    def execute(self):
        print("job executed at 4:00 Am")

Any help will be highly appreciated

2

There are 2 best solutions below

1
Jamie Counsell On

Django doesn't handle the timing, crontab does.

As long as you're ok with all daily jobs running at 4am you can just update your crontab to use that. The docs show:

@daily /path/to/my/project/manage.py runjobs daily

And these docs show that @daily is equivalent to 0 0 * * *.

So just change your crontab to:

0 4 * * * /path/to/my/project/manage.py runjobs daily

Their source code also shows there is a runjob command which can take a job name. So to run just that job at 4am, you would use:

0 4 * * * /path/to/my/project/manage.py runjob my_job

However, this job must not be a DailyJob then, since it would run twice (once daily from runjobs daily, once at 4am from runjob myjob). I think to do this, you would just inherit from BaseJob instead:

class Job(BaseJob):
    help = "Send notification On Instruction Instances"

But I am not 100% sure where this would go in your code. I'd probably start by trying to add it directly under the jobs/ directory.

1
michjnich On

The first answer is correct, but just to add a few more options for you, there are django packages that handle background tasks and scheduling quite nicely, ranging from simple stuff that just kicks of a task when you want, to complex solutions like celery.

Check out https://djangopackages.org/grids/g/workers-queues-tasks/ for a full list of packages you may find useful here.