Run celery tasks by name

Usually celery tasks will be triggered by calling the celery task function.  An overhead with this approach is that the task function should be imported in the module/view file, from where the function can be called to perform the task. 

Perhaps the task needs to be allowed to be triggered from multiple module/view files, all of that files needs to be imported with the task function.

Celery provides an option to handle the above kind of requirement. Task can be triggered from any modules or view files by just importing the send_task method from standard celery library and by just using the task name, the tasks can be triggered.

Code Sample: To understand the method to run celery task by name
#File: Any module/view file

from celery.execute import send_task    

send_task('manage_service', 'ntpd', action='restart')

# syntax: send_task(taskname, *args, **kwargs)
#File: task.py 

from celery import task 
import os 

@task(name='manage_service') 
def manage_service(serviceName, action='start'):
    os.system('service %s %s' %(serviceName, action))

The send_task method can also be called via celery.current_app.send_task

Note:
Celery assigns default name for the tasks, when the task name not defined in the task decorator in task.py as per the above code sample. The default task name would contain the task function name along withe module hierarchy, for example "app.services.task.manage_service".


Post a Comment

0 Comments