12

I want to run this function everyday midnight to check expiry_date_notification. what can I do? I'm new to django and 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()
nabeel
  • 1,181
  • 2
  • 10
  • 24

3 Answers3

27

As others have said, 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")

Install via pip install django-celery

Josh
  • 7,936
  • 5
  • 41
  • 63
  • 8
    Just a reminder for Googler: Celery now supports Django, so no need to install `django-celery`. Just install Celery. Check the documentation: https://docs.celeryproject.org/en/latest/django/first-steps-with-django.html – Eray Erdin May 09 '19 at 12:56
3

You can either write a custom management command and schedule its execution using cron, or you can use celery.

samu
  • 2,870
  • 16
  • 28
  • I'm planning to to it in custom management command..But what kind of function should I give in Basecommand inherted class?? – nabeel May 09 '14 at 15:21
  • I don't really want to create another answer, so I'll just try to fit in the comment. Just create a class that inherits from *BaseCommand*, create string attributes: *args* and *help* containing a short description/syntax information for manage.py --help. Then, define a *handle* method... and that's it. In that method you can import your function and simply execute it. I can see that this function is *probably* a view right now. But, as I look at its body, it doesn't really make use of the request object, so you can just leave it argumentless and just call it. – samu May 09 '14 at 19:22
1

Have a look at:

Celery - Distributed Task Queue

grigno
  • 3,128
  • 4
  • 35
  • 47