Search code examples
djangocelerypython-3.7celerybeat

Celery task not starting at the start time provided


I have a Django app that utilizes celery in order to handle user scheduled tasks. I'm currently having a problem where I set start time for the PerodicTask and it does not start at that specific time, rather sometime later instead.

Environment:

  • Celery 4.3
  • Django 2.2
  • Python 3.7
task = PeriodicTask(name="foo",task="bar_task",
                    start_time=DateTime5MinutesAhead, 
                    interval=EveryHourInterval)
task.save()

I expect the task run first in 5 minutes from when the task was created and then every hour after that. Instead, it seems to run at some arbitrary point later, completely ignoring the start_time argument.

Am I mistaken on what the start_time argument is for?

I've tried with IntervalSchedule as well as CrontabSchedule

and neither seem to start at the exact start time.

Bonus: What's actually really weird in my findings is that if I use IntervalSchedule set to every minute it actually DOES, in fact, start on correctly and run correctly, but if I set it to anything else it no longer works.


Solution

  • you need to set last_run_at to start_time - interval

            task = PeriodicTask(name="foo",task="bar_task",
                    start_time=DateTime5MinutesAhead,
                    last_run_at=DateTime5MinutesAhead - timedelta(hour=1),
                    interval=EveryHourInterval)
            task.save()
    

    not sure if its a bug or a feature but worked fine for me,

    reference: https://github.com/celery/django-celery-beat/issues/259