How to create a task with Celery
In this recipe, we'll show you how to create and call a task using the Celery module. Celery provides the following methods that make a call to a task:
apply_async(args[, kwargs[, …]]): This task sends a task messagedelay(*args, **kwargs): This is a shortcut to send a task message, but does not support execution options
The delay method is better to use because it can be called as a regular function:
task.delay(arg1, arg2, kwarg1='x', kwarg2='y')
While using apply_async you should write:
task.apply_async (args=[arg1, arg2] kwargs={'kwarg1': 'x','kwarg2': 'y'})How to do it…
To perform this simple task, we implement the following two simple scripts:
###
## addTask.py :Executing a simple task
###
from celery import Celery
app = Celery('addTask',broker='amqp://guest@localhost/')
@app.task
def add(x, y):
return x + y
while the second script is :
###
#addTask.py...
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at AU $24.99/month. Cancel anytime