abortable.py 4.9 KB

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