Run tasks every day at 8am in Django on Windows

7.7k views Asked by At

I am working on a web app in Django and I need to send some random numbers to the database every day at 8am.

I have tried to use celery but it has not worked. I am using windows and from a tutorial I understand celery does not work on windows.

I have tried using django-extensions and django-cron but it needs changes made to the linux cron and as I said before, I am on windows.

How should I solve this? Any help would be appreciated.

4

There are 4 answers

0
Farzan On BEST ANSWER

Finally I've found a good way to do the job. In same situations like mine, you can use APScheduler as a strong tool when scheduling is needed:

https://apscheduler.readthedocs.io/en/stable/index.html


Update :

For doing some jobs periodically, you can also use Schedule as a simple and useful tool: https://schedule.readthedocs.io/en/stable/

0
knl On

I was in your current situation about a year ago. I was looking around for a background scheduled task solution for Django on Windows but it seems nothing stands out.

Have a look into these:

Or simply, just use Windows Task Scheduler to execute python script, however, the two packages above help you to execute long running task on demand from Django, or set schedule from Django as well.

0
alec_djinn On

Unless you really need a scheduler, I would simply use something like this:

import time, datetime

while True:
    now = datetime.datetime.now()
    if now.hour == 8 and now.minute == 0:
        send_rnd_numbers_to_database()
        time.sleep(24*60*60 - 120) #sleep almost 24h
    else:
        time.sleep(15) #check every X seconds, adjust as you need

After the first numbers are sent, it will sleep and wake up just a few minutes before 8:00. Then it will check as often you would like.

You can run this a thread, a subprocess, or just as a script separate from your application. You can add a try/except block around your function if needed, as well as a timeout handling.

0
Dan Yishai On

Try django-windowsauth and the createtask command. You can use it to create Windows Task Scheduler jobs for Django management commands easily.

https://django-windowsauth.readthedocs.io/en/latest/howto/create_tasks.html

To do so, create a new custom management command for your app: https://docs.djangoproject.com/en/3.1/howto/custom-management-commands/

Then run: > py manage.py createtask your_custom_task -i days=1

Open Windows Task Scheduler (search Scheduler in start menu), open the new created job, edit the trigger start time to 8:00 AM.