如何每周安排 Django shell 命令?

How to schedule Django shell command every week?

我试图让某个 Python 脚本每周在 Django shell 中运行 运行。我怎样才能做到这一点?我读过有关 cron 和 django-rq 的内容,但我认为在给定参数内这是不可能的。

提前致谢!

PS.: 有问题的代码,它只是删除旧数据库并添加更新的数据库:

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()

这正是 cron 的用途。

而不是使用单独的 python 脚本创建 django 命令。创建 your_app/commands/remove_db.py 文件。

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

然后,在命令行中:

$ python manage.py remove_db

现在,使用 crontab 可以很容易地向 Linux 系统添加新的 cron 任务:

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