I need to call a celery task (in tasks.py) from models.py, the only problem is, tasks.py imports models.py, so I can't import tasks.py from models.py.
Is there some way to call a celery task simply using its name, without having to import it? A similar thing is implemented for ForeignKey fields for the same reason (preventing circular imports).
Celery does not require access to a task's code base in order to invoke it. The trick is to invoke a task by its name, either directly via celery_app. send_task(...) or by creating a Signature object celery_app. signature(...) which is the equivalent of calling task.
To answer your opening questions: As of version 2.0, Celery provides an easy way to start tasks from other tasks. What you are calling "secondary tasks" are what it calls "subtasks".
This way, you delegate queue creation to Celery. You can use apply_async with any queue and Celery will handle it, provided your task is aware of the queue used by apply_async . If none is provided then the worker will listen only for the default queue.
Yes, there is.
You can use:
from celery.execute import send_task
send_task('my_task', [], kwargs)
Be sure that you task function has a name:
from celery import task
@task(name='my_task')
def my_task():
...
Hope it helps!
In Celery 3+:
from celery import Celery
app = Celery()
app.send_task('my_task', [], kwargs)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With