Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

abortable.py 5.0KB

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