Search code examples
djangocelerycelerybeat

Celery Beat how to calculate difference between datetime.now() and the next scheduled Periodic Task django


I have a celery beat cron schedule set for day 3 of every week. In django shell I can access this schedule:

    >>> schedule = PeriodicTask.objects.get(name="Bulk Newsletter Send")
    which results in:
    >>> <PeriodicTask: Bulk Newsletter Send: * * * * 3 (m/h/dM/MY/d) UTC>

My question is, how can I calculate the time difference in days between datetime.now() and the next PeriodicTask?


Solution

  • This is the solution that I am going to run with:

    Derived from Celery docs celery.schedules

    periodic_task = PeriodicTask.objects.get(name="my_task")
    
    time_to_go = periodic_task.schedule.is_due(datetime.now())
    
    time_to_go.next = time to next run in seconds