Django - 如何运行函数EVERYDAY?

nab*_*eel 7 django recurrence notifications date django-timezone

我想每天午夜运行这个功能来检查expiry_date_notification.我能做什么?我是django和python的新手.

def check_expiry_date(request):
    products = Product.objects.all()
    for product in products:
        product_id = product.id
        expiry_date = product.expiry_date
        notification_days = product.notification_days
        check_date = int((expiry_date - datetime.datetime.today()).days)
        if notification_days <= check_date:
            notification = Notification(product_id=product_id)
            notification.save()
Run Code Online (Sandbox Code Playgroud)

Jos*_*osh 11

正如其他人所说,Celery可以安排任务在特定时间执行.

from celery.schedules import crontab
from celery.task import periodic_task

@periodic_task(run_every=crontab(hour=7, minute=30, day_of_week="mon"))
def every_monday_morning():
    print("This is run every Monday morning at 7:30")
Run Code Online (Sandbox Code Playgroud)

通过安装 pip install django-celery

  • 提醒 Google 员工:Celery 现在支持 Django,因此无需安装 `django-celery`。只需安装芹菜。检查文档:https://docs.celeryproject.org/en/latest/django/first-steps-with-django.html (6认同)
  • 我应该将此代码放在django的哪个文件中? (3认同)