Home > Software engineering >  How to schedule Django shell command every week?
How to schedule Django shell command every week?

Time:02-23

I'm trying to let a certain Python script run every week in the Django shell. How can I accomplish this? I've read about cron & django-rq, but I don't think this is possible within the given parameters.

Thanks in advance!

PS.: the code in question, it just deletes the old database and adds the updated one:

from formcheck.models import FormCheck
import csv

FormCheck.objects.all().delete()

formcheck_csv = open('PolisCheck.csv', 'r', encoding = "utf-8") 
reader = csv.reader(formcheck_csv)
headers = next(reader, None)[1:]

for row in reader:  
   polis_dict = {}
   for h, val in zip(headers, row[1:]):
      polis_dict[h] = val
   formcheck = FormCheck.objects.create(**polis_dict)

formcheck_csv.close()  
exit()

CodePudding user response:

That's exactly what the cron is for.

Instead of having separate python script create django command. Create your_app/commands/remove_db.py file.

from django.core.management.base import BaseCommand, CommandError

class Command(BaseCommand):
    args = ''
    help = 'Remove old database'

    def handle(self, *args, **options):
        # put your removal logic here

And then, in the command line:

$ python manage.py remove_db

Now, it's easy to add a new cron task to a Linux system, using crontab:

# m h  dom mon dow   command
0 0 * * 0 python /var/www/myapp/manage.py remove_db
  • Related