Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Django celery task by name

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).

like image 801
Mark P Avatar asked Oct 08 '13 04:10

Mark P


People also ask

How do you call celery task?

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.

Can a celery task call another 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".

What is Apply_async in celery?

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.


2 Answers

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!

like image 124
Jotakun Avatar answered Nov 14 '22 17:11

Jotakun


In Celery 3+:

from celery import Celery

app = Celery()
app.send_task('my_task', [], kwargs)
like image 35
Kamil Sindi Avatar answered Nov 14 '22 18:11

Kamil Sindi