lampslave
lampslave

Reputation: 1503

What is the difference between applying, running and calling of celery task?

What is the difference between mytask.apply(), mytask.run() and mytask()? Which way is preferable?

Upvotes: 22

Views: 15892

Answers (2)

g4borg
g4borg

Reputation: 163

You can find all of this in the celery package in celery/app/task.py, or in the documentation http://docs.celeryproject.org/en/latest/reference/celery.app.task.html

To elaborate in my own investigation:

  • run is the immediate (local blocking) form of delay with the same limitations (arguments get passed, however no access to other execution options), and is similar to calling. it will immediately return e.g. in case of an exception, so the call is fully blocking, and just like calling a function.
tasks.my_task.run(foo='bar')

my_task() is the documented one, and acts like run. (in fact, Task.__call__ executes self.run(*args, **kwargs)); It should be probably preferred over run(), as it does other things as well.

tasks.my_task(foo='bar')

so between mytask.run() and mytask() i would choose mytask(), except if i know i want run instead. If it would be rewritten, as true celery worker function, both would be rewritten as delay()

  • apply is the form which uses a syntax akin to apply_async. so your arguments are added as args/kwargs keywords:
tasks.my_task.apply(kwargs={'foo': 'bar'})

it is also the function called by apply_async if it is set to always_eager. A side effect is, that exceptions would continue execution, just as apply_async would, if it is not set to always_eager or gets the throw keyword set.

when i want to have a syntax which later gets changed into apply_async, i would prefer apply - generally i would prefer apply personally.

Upvotes: 15

Cheney
Cheney

Reputation: 980

In my understanding:

  • apply: is to call task and execute locally
  • run: never seen before
  • mytask(): just like call func

If you want to send message and execute remote,you should use apply_async or delay, referring call_task.

Upvotes: 5

Related Questions