Search code examples
djangocelerydjango-celery-beat

django-celery-beat and DatabaseScheduler with a set first run time


I want to use django-celery-beat and DatabaseScheduler to create an "email alert" function for users. They should be able to say, when they want to receive these alerts (e.g. every day - 7 AM or every week monday 1 PM).

I've almost figured out how to create the periodic tasks, i.e.

>>> PeriodicTask.objects.create(
...     interval=schedule,                  # we created this above.
...     name='Importing contacts',          # simply describes this periodic task.
...     task='proj.tasks.import_contacts',  # name of task.
...     expires=datetime.utcnow() + timedelta(seconds=30)
... )

from https://github.com/celery/django-celery-beat, but how do I tell it when the first sendout should be?


Solution

  • There is a field start_time in PeriodicTask model. You can set a datetime value for it. The task will be first sent after at that time.

    >>> PeriodicTask.objects.create(
            # skipped
            start_time=datetime.utcnow() + timedelta(seconds=300)
            # task will be first sent after 5 minutes
    )