Django - 如何运行函数EVERYDAY?

时间:2014-05-09 11:52:09

标签: django date notifications recurrence 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()

3 个答案:

答案 0 :(得分:10)

正如其他人所说,Celery can schedule tasks to execute at a specific time

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

通过pip install django-celery

安装

答案 1 :(得分:3)

您可以编写custom management command并使用cron安排执行,也可以使用celery

答案 2 :(得分:1)