deferred.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
  2. # Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
  3. # Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU Affero General Public License as
  6. # published by the Free Software Foundation, either version 3 of the
  7. # License, or (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU Affero General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU Affero General Public License
  15. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. from django.conf import settings
  17. from .celery import app
  18. def _send_task(task, args, kwargs, **options):
  19. if settings.CELERY_ALWAYS_EAGER:
  20. return app.tasks[task].apply(args, kwargs, **options)
  21. return app.send_task(task, args, kwargs, **options)
  22. def defer(task: str, *args, **kwargs):
  23. """Defer the execution of a task.
  24. Defer the execution of a task and returns a future objects with the following methods among
  25. others:
  26. - `failed()` Returns `True` if the task failed.
  27. - `ready()` Returns `True` if the task has been executed.
  28. - `forget()` Forget about the result.
  29. - `get()` Wait until the task is ready and return its result.
  30. - `result` When the task has been executed the result is in this attribute.
  31. More info at Celery docs on `AsyncResult` object.
  32. :param task: Name of the task to execute.
  33. :return: A future object.
  34. """
  35. return _send_task(task, args, kwargs, routing_key="transient.deferred")
  36. def call_async(task: str, *args, **kwargs):
  37. """Run a task and ignore its result.
  38. This is just a star argument version of `apply_async`.
  39. :param task: Name of the task to execute.
  40. :param args: Arguments for the task.
  41. :param kwargs: Keyword arguments for the task.
  42. """
  43. apply_async(task, args, kwargs)
  44. def apply_async(task: str, args=None, kwargs=None, **options):
  45. """Run a task and ignore its result.
  46. :param task: Name of the task to execute.
  47. :param args: Tupple of arguments for the task.
  48. :param kwargs: Dict of keyword arguments for the task.
  49. :param options: Celery-specific options when running the task. See Celery docs on `apply_async`
  50. """
  51. _send_task(task, args, kwargs, **options)