abortable.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. # -*- coding: utf-8 -*-
  2. """Abortable Tasks.
  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. from celery.utils.log import get_task_logger
  23. from proj.celery import app
  24. logger = get_logger(__name__)
  25. @app.task(bind=True, base=AbortableTask)
  26. def long_running_task(self):
  27. results = []
  28. for i in range(100):
  29. # check after every 5 iterations...
  30. # (or alternatively, check when some timer is due)
  31. if not i % 5:
  32. if self.is_aborted():
  33. # respect aborted state, and terminate gracefully.
  34. logger.warning('Task aborted')
  35. return
  36. value = do_something_expensive(i)
  37. results.append(y)
  38. logger.info('Task complete')
  39. return results
  40. In the producer:
  41. .. code-block:: python
  42. import time
  43. from proj.tasks import MyLongRunningTask
  44. def myview(request):
  45. # result is of type AbortableAsyncResult
  46. result = long_running_task.delay()
  47. # abort the task after 10 seconds
  48. time.sleep(10)
  49. result.abort()
  50. After the `result.abort()` call, the task execution is not
  51. aborted immediately. In fact, it is not guaranteed to abort at all. Keep
  52. checking `result.state` status, or call `result.get(timeout=)` 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 celery import Task
  61. from celery.result import AsyncResult
  62. __all__ = ['AbortableAsyncResult', 'AbortableTask']
  63. """
  64. Task States
  65. -----------
  66. .. state:: ABORTED
  67. ABORTED
  68. ~~~~~~~
  69. Task is aborted (typically by the producer) and should be
  70. aborted as soon as possible.
  71. """
  72. ABORTED = 'ABORTED'
  73. class AbortableAsyncResult(AsyncResult):
  74. """Represents a abortable result.
  75. Specifically, this gives the `AsyncResult` a :meth:`abort()` method,
  76. which sets the state of the underlying Task to `'ABORTED'`.
  77. """
  78. def is_aborted(self):
  79. """Return :const:`True` if the task is (being) aborted."""
  80. return self.state == ABORTED
  81. def abort(self):
  82. """Set the state of the task to :const:`ABORTED`.
  83. Abortable tasks monitor their state at regular intervals and
  84. terminate execution if so.
  85. Warning:
  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 all).
  88. """
  89. # TODO: store_result requires all four arguments to be set,
  90. # but only state should be updated here
  91. return self.backend.store_result(self.id, result=None,
  92. state=ABORTED, traceback=None)
  93. class AbortableTask(Task):
  94. """A celery task that serves as a base class for all :class:`Task`'s
  95. that support aborting during execution.
  96. All subclasses of :class:`AbortableTask` must call the
  97. :meth:`is_aborted` method periodically and act accordingly when
  98. the call evaluates to :const:`True`.
  99. """
  100. abstract = True
  101. def AsyncResult(self, task_id):
  102. """Return the accompanying AbortableAsyncResult instance."""
  103. return AbortableAsyncResult(task_id, backend=self.backend)
  104. def is_aborted(self, **kwargs):
  105. """Checks against the backend whether this
  106. :class:`AbortableAsyncResult` is :const:`ABORTED`.
  107. Always return :const:`False` in case the `task_id` parameter
  108. refers to a regular (non-abortable) :class:`Task`.
  109. Be aware that invoking this method will cause a hit in the
  110. backend (for example a database query), so find a good balance
  111. between calling it regularly (for responsiveness), but not too
  112. often (for performance).
  113. """
  114. task_id = kwargs.get('task_id', self.request.id)
  115. result = self.AsyncResult(task_id)
  116. if not isinstance(result, AbortableAsyncResult):
  117. return False
  118. return result.is_aborted()