If I have a function defined as follows:
def add(x,y):
return x+y
Is there a way to dynamically add this function as a celery PeriodicTask and kick it off at runtime? I'd like to be able to do something like (pseudocode):
some_unique_task_id = celery.beat.schedule_task(add, run_every=crontab(minute="*/30"))
celery.beat.start(some_unique_task_id)
I would also want to stop or remove that task dynamically with something like (pseudocode):
celery.beat.remove_task(some_unique_task_id)
or
celery.beat.stop(some_unique_task_id)
FYI I am not using djcelery, which lets you manage periodic tasks via the django admin.
This question was answered on google groups.
I AM NOT THE AUTHOR, all credit goes to Jean Mark
There is a library called django-celery-beat which provides the models one needs. To make it dynamically load new periodic tasks one has to create its own Scheduler.
This was finally made possible by a fix included in celery v4.1.0. Now, you just need to change the schedule entries in the database backend, and celery-beat will act according to the new schedule.
The docs vaguely describe how this works. The default scheduler for celery-beat,
PersistentScheduler
, uses a shelve file as its schedule database. Any changes to thebeat_schedule
dictionary in thePersistentScheduler
instance are synced with this database (by default, every 3 minutes), and vice-versa. The docs describe how to add new entries to thebeat_schedule
usingapp.add_periodic_task
. To modify an existing entry, just add a new entry with the samename
. Delete an entry as you would from a dictionary:del app.conf.beat_schedule['name']
.Suppose you want to monitor and modify your celery beat schedule using an external app. Then you have several options:
open
the shelve database file and read its contents like a dictionary. Write back to this file for modifications.You can check out this flask-djcelery which configures flask and djcelery and also provides browseable rest api
No, I'm sorry, this is not possible with the regular celerybeat.
But it's easily extensible to do what you want, e.g. the django-celery scheduler is just a subclass reading and writing the schedule to the database (with some optimizations on top).
Also you can use the django-celery scheduler even for non-Django projects.
Something like this:
Install django + django-celery:
$ pip install -U django django-celery
Add the following settings to your celeryconfig:
Create the database tables:
Start celerybeat with the database scheduler:
Also there's the
djcelerymon
command which can be used for non-Django projects to start celerycam and a Django Admin webserver in the same process, you can use that to also edit your periodic tasks in a nice web interface:(Note for some reason djcelerymon can't be stopped using Ctrl+C, you have to use Ctrl+Z + kill %1)