abortable.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. """
  2. =========================
  3. Abortable tasks overview
  4. =========================
  5. For long-running :class:`Task`'s, it can be desirable to support
  6. aborting during execution. Of course, these tasks should be built to
  7. support abortion specifically.
  8. The :class:`AbortableTask` serves as a base class for all :class:`Task`
  9. objects that should support abortion by producers.
  10. * Producers may invoke the :meth:`abort` method on
  11. :class:`AbortableAsyncResult` instances, to request abortion.
  12. * Consumers (workers) should periodically check (and honor!) the
  13. :meth:`is_aborted` method at controlled points in their task's
  14. :meth:`run` method. The more often, the better.
  15. The necessary intermediate communication is dealt with by the
  16. :class:`AbortableTask` implementation.
  17. Usage example
  18. -------------
  19. In the consumer:
  20. .. code-block:: python
  21. from celery.contrib.abortable import AbortableTask
  22. def MyLongRunningTask(AbortableTask):
  23. def run(self, **kwargs):
  24. logger = self.get_logger(**kwargs)
  25. results = []
  26. for x in xrange(100):
  27. # Check after every 5 loops..
  28. if x % 5 == 0: # alternatively, check when some timer is due
  29. if self.is_aborted(**kwargs):
  30. # Respect the aborted status and terminate
  31. # gracefully
  32. logger.warning("Task aborted.")
  33. return None
  34. y = do_something_expensive(x)
  35. results.append(y)
  36. logger.info("Task finished.")
  37. return results
  38. In the producer:
  39. .. code-block:: python
  40. from myproject.tasks import MyLongRunningTask
  41. def myview(request):
  42. async_result = MyLongRunningTask.delay()
  43. # async_result is of type AbortableAsyncResult
  44. # After 10 seconds, abort the task
  45. time.sleep(10)
  46. async_result.abort()
  47. ...
  48. After the `async_result.abort()` call, the task execution is not
  49. aborted immediately. In fact, it is not guaranteed to abort at all. Keep
  50. checking the `async_result` status, or call `async_result.wait()` to
  51. have it block until the task is finished.
  52. .. note::
  53. In order to abort tasks, there needs to be communication between the
  54. producer and the consumer. This is currently implemented through the
  55. database backend. Therefore, this class will only work with the
  56. database backends.
  57. """
  58. from celery.task.base import Task
  59. from celery.result import AsyncResult
  60. """
  61. Task States
  62. -----------
  63. .. state:: ABORTED
  64. ABORTED
  65. ~~~~~~~
  66. Task is aborted (typically by the producer) and should be
  67. aborted as soon as possible.
  68. """
  69. ABORTED = "ABORTED"
  70. class AbortableAsyncResult(AsyncResult):
  71. """Represents a abortable result.
  72. Specifically, this gives the `AsyncResult` a :meth:`abort()` method,
  73. which sets the state of the underlying Task to `"ABORTED"`.
  74. """
  75. def is_aborted(self):
  76. """Returns :const:`True` if the task is (being) aborted."""
  77. return self.backend.get_status(self.task_id) == ABORTED
  78. def abort(self):
  79. """Set the state of the task to :const:`ABORTED`.
  80. Abortable tasks monitor their state at regular intervals and
  81. terminate execution if so.
  82. Be aware that invoking this method does not guarantee when the
  83. task will be aborted (or even if the task will be aborted at
  84. all).
  85. """
  86. # TODO: store_result requires all four arguments to be set,
  87. # but only status should be updated here
  88. return self.backend.store_result(self.task_id, result=None,
  89. status=ABORTED, traceback=None)
  90. class AbortableTask(Task):
  91. """A celery task that serves as a base class for all :class:`Task`'s
  92. that support aborting during execution.
  93. All subclasses of :class:`AbortableTask` must call the
  94. :meth:`is_aborted` method periodically and act accordingly when
  95. the call evaluates to :const:`True`.
  96. """
  97. @classmethod
  98. def AsyncResult(cls, task_id):
  99. """Returns the accompanying AbortableAsyncResult instance."""
  100. return AbortableAsyncResult(task_id, backend=cls.backend)
  101. def is_aborted(self, **kwargs):
  102. """Checks against the backend whether this
  103. :class:`AbortableAsyncResult` is :const:`ABORTED`.
  104. Always returns :const:`False` in case the `task_id` parameter
  105. refers to a regular (non-abortable) :class:`Task`.
  106. Be aware that invoking this method will cause a hit in the
  107. backend (for example a database query), so find a good balance
  108. between calling it regularly (for responsiveness), but not too
  109. often (for performance).
  110. """
  111. result = self.AsyncResult(kwargs["task_id"])
  112. if not isinstance(result, AbortableAsyncResult):
  113. return False
  114. return result.is_aborted()