base.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  1. # -*- coding: utf-8 -*-"
  2. import sys
  3. import threading
  4. from celery import current_app
  5. from celery.datastructures import ExceptionInfo
  6. from celery.exceptions import MaxRetriesExceededError, RetryTaskError
  7. from celery.execute.trace import TaskTrace
  8. from celery.registry import tasks, _unpickle_task
  9. from celery.result import EagerResult
  10. from celery.schedules import maybe_schedule
  11. from celery.utils import deprecated, mattrgetter, gen_unique_id, \
  12. fun_takes_kwargs
  13. from celery.utils import timeutils
  14. @deprecated("Importing TaskSet from celery.task.base",
  15. alternative="Use celery.task.TaskSet instead.",
  16. removal="2.4")
  17. def TaskSet(*args, **kwargs):
  18. from celery.task.sets import TaskSet
  19. return TaskSet(*args, **kwargs)
  20. @deprecated("Importing subtask from celery.task.base",
  21. alternative="Use celery.task.subtask instead.",
  22. removal="2.4")
  23. def subtask(*args, **kwargs):
  24. from celery.task.sets import subtask
  25. return subtask(*args, **kwargs)
  26. extract_exec_options = mattrgetter("queue", "routing_key",
  27. "exchange", "immediate",
  28. "mandatory", "priority",
  29. "serializer", "delivery_mode",
  30. "compression")
  31. class Context(threading.local):
  32. # Default context
  33. logfile = None
  34. loglevel = None
  35. id = None
  36. args = None
  37. kwargs = None
  38. retries = 0
  39. is_eager = False
  40. delivery_info = None
  41. taskset = None
  42. def update(self, d, **kwargs):
  43. self.__dict__.update(d, **kwargs)
  44. def clear(self):
  45. self.__dict__.clear()
  46. def get(self, key, default=None):
  47. if not hasattr(self, key):
  48. return default
  49. return getattr(self, key)
  50. class TaskType(type):
  51. """Metaclass for tasks.
  52. Automatically registers the task in the task registry, except
  53. if the `abstract` attribute is set.
  54. If no `name` attribute is provided, the name is automatically
  55. set to the name of the module it was defined in, and the class name.
  56. """
  57. def __new__(cls, name, bases, attrs):
  58. new = super(TaskType, cls).__new__
  59. task_module = attrs.get("__module__") or "__main__"
  60. # Abstract class: abstract attribute should not be inherited.
  61. if attrs.pop("abstract", None) or not attrs.get("autoregister", True):
  62. return new(cls, name, bases, attrs)
  63. # Automatically generate missing/empty name.
  64. autoname = False
  65. if not attrs.get("name"):
  66. try:
  67. module_name = sys.modules[task_module].__name__
  68. except KeyError:
  69. # Fix for manage.py shell_plus (Issue #366).
  70. module_name = task_module
  71. attrs["name"] = '.'.join([module_name, name])
  72. autoname = True
  73. # Because of the way import happens (recursively)
  74. # we may or may not be the first time the task tries to register
  75. # with the framework. There should only be one class for each task
  76. # name, so we always return the registered version.
  77. task_name = attrs["name"]
  78. if task_name not in tasks:
  79. task_cls = new(cls, name, bases, attrs)
  80. if autoname and task_module == "__main__" and task_cls.app.main:
  81. task_name = task_cls.name = '.'.join([task_cls.app.main, name])
  82. tasks.register(task_cls)
  83. task = tasks[task_name].__class__
  84. return task
  85. def __repr__(cls):
  86. return "<class Task of %s>" % (cls.app, )
  87. class BaseTask(object):
  88. """Task base class.
  89. When called tasks apply the :meth:`run` method. This method must
  90. be defined by all tasks (that is unless the :meth:`__call__` method
  91. is overridden).
  92. """
  93. __metaclass__ = TaskType
  94. MaxRetriesExceededError = MaxRetriesExceededError
  95. #: The application instance associated with this task class.
  96. app = None
  97. #: Name of the task.
  98. name = None
  99. #: If :const:`True` the task is an abstract base class.
  100. abstract = True
  101. #: If disabled the worker will not forward magic keyword arguments.
  102. #: Deprecated and scheduled for removal in v3.0.
  103. accept_magic_kwargs = False
  104. #: Request context (set when task is applied).
  105. request = Context()
  106. #: Destination queue. The queue needs to exist
  107. #: in :setting:`CELERY_QUEUES`. The `routing_key`, `exchange` and
  108. #: `exchange_type` attributes will be ignored if this is set.
  109. queue = None
  110. #: Overrides the apps default `routing_key` for this task.
  111. routing_key = None
  112. #: Overrides the apps default `exchange` for this task.
  113. exchange = None
  114. #: Overrides the apps default exchange type for this task.
  115. exchange_type = None
  116. #: Override the apps default delivery mode for this task. Default is
  117. #: `"persistent"`, but you can change this to `"transient"`, which means
  118. #: messages will be lost if the broker is restarted. Consult your broker
  119. #: manual for any additional delivery modes.
  120. delivery_mode = None
  121. #: Mandatory message routing.
  122. mandatory = False
  123. #: Request immediate delivery.
  124. immediate = False
  125. #: Default message priority. A number between 0 to 9, where 0 is the
  126. #: highest. Note that RabbitMQ does not support priorities.
  127. priority = None
  128. #: Maximum number of retries before giving up. If set to :const:`None`,
  129. #: it will **never** stop retrying.
  130. max_retries = 3
  131. #: Default time in seconds before a retry of the task should be
  132. #: executed. 3 minutes by default.
  133. default_retry_delay = 3 * 60
  134. #: Rate limit for this task type. Examples: :const:`None` (no rate
  135. #: limit), `"100/s"` (hundred tasks a second), `"100/m"` (hundred tasks
  136. #: a minute),`"100/h"` (hundred tasks an hour)
  137. rate_limit = None
  138. #: If enabled the worker will not store task state and return values
  139. #: for this task. Defaults to the :setting:`CELERY_IGNORE_RESULT`
  140. #: setting.
  141. ignore_result = False
  142. #: When enabled errors will be stored even if the task is otherwise
  143. #: configured to ignore results.
  144. store_errors_even_if_ignored = False
  145. #: If enabled an e-mail will be sent to :setting:`ADMINS` whenever a task
  146. #: of this type fails.
  147. send_error_emails = False
  148. disable_error_emails = False # FIXME
  149. #: List of exception types to send error e-mails for.
  150. error_whitelist = ()
  151. #: The name of a serializer that are registered with
  152. #: :mod:`kombu.serialization.registry`. Default is `"pickle"`.
  153. serializer = "pickle"
  154. #: The result store backend used for this task.
  155. backend = None
  156. #: If disabled this task won't be registered automatically.
  157. autoregister = True
  158. #: If enabled the task will report its status as "started" when the task
  159. #: is executed by a worker. Disabled by default as the normal behaviour
  160. #: is to not report that level of granularity. Tasks are either pending,
  161. #: finished, or waiting to be retried.
  162. #:
  163. #: Having a "started" status can be useful for when there are long
  164. #: running tasks and there is a need to report which task is currently
  165. #: running.
  166. #:
  167. #: The application default can be overridden using the
  168. #: :setting:`CELERY_TRACK_STARTED` setting.
  169. track_started = False
  170. #: When enabled messages for this task will be acknowledged **after**
  171. #: the task has been executed, and not *just before* which is the
  172. #: default behavior.
  173. #:
  174. #: Please note that this means the task may be executed twice if the
  175. #: worker crashes mid execution (which may be acceptable for some
  176. #: applications).
  177. #:
  178. #: The application default can be overriden with the
  179. #: :setting:`CELERY_ACKS_LATE` setting.
  180. acks_late = False
  181. #: Default task expiry time.
  182. expires = None
  183. #: The type of task *(no longer used)*.
  184. type = "regular"
  185. def __call__(self, *args, **kwargs):
  186. return self.run(*args, **kwargs)
  187. def __reduce__(self):
  188. return (_unpickle_task, (self.name, ), None)
  189. def run(self, *args, **kwargs):
  190. """The body of the task executed by workers."""
  191. raise NotImplementedError("Tasks must define the run method.")
  192. @classmethod
  193. def get_logger(self, loglevel=None, logfile=None, propagate=False,
  194. **kwargs):
  195. """Get task-aware logger object."""
  196. if loglevel is None:
  197. loglevel = self.request.loglevel
  198. if logfile is None:
  199. logfile = self.request.logfile
  200. return self.app.log.setup_task_logger(loglevel=loglevel,
  201. logfile=logfile,
  202. propagate=propagate,
  203. task_name=self.name,
  204. task_id=self.request.id)
  205. @classmethod
  206. def establish_connection(self, connect_timeout=None):
  207. """Establish a connection to the message broker."""
  208. return self.app.broker_connection(connect_timeout=connect_timeout)
  209. @classmethod
  210. def get_publisher(self, connection=None, exchange=None,
  211. connect_timeout=None, exchange_type=None, **options):
  212. """Get a celery task message publisher.
  213. :rtype :class:`~celery.app.amqp.TaskPublisher`:
  214. .. warning::
  215. If you don't specify a connection, one will automatically
  216. be established for you, in that case you need to close this
  217. connection after use::
  218. >>> publisher = self.get_publisher()
  219. >>> # ... do something with publisher
  220. >>> publisher.connection.close()
  221. or used as a context::
  222. >>> with self.get_publisher() as publisher:
  223. ... # ... do something with publisher
  224. """
  225. if exchange is None:
  226. exchange = self.exchange
  227. if exchange_type is None:
  228. exchange_type = self.exchange_type
  229. connection = connection or self.establish_connection(connect_timeout)
  230. return self.app.amqp.TaskPublisher(connection=connection,
  231. exchange=exchange,
  232. exchange_type=exchange_type,
  233. routing_key=self.routing_key,
  234. **options)
  235. @classmethod
  236. def get_consumer(self, connection=None, connect_timeout=None):
  237. """Get message consumer.
  238. :rtype :class:`kombu.messaging.Consumer`:
  239. .. warning::
  240. If you don't specify a connection, one will automatically
  241. be established for you, in that case you need to close this
  242. connection after use::
  243. >>> consumer = self.get_consumer()
  244. >>> # do something with consumer
  245. >>> consumer.close()
  246. >>> consumer.connection.close()
  247. """
  248. connection = connection or self.establish_connection(connect_timeout)
  249. return self.app.amqp.TaskConsumer(connection=connection,
  250. exchange=self.exchange,
  251. routing_key=self.routing_key)
  252. @classmethod
  253. def delay(self, *args, **kwargs):
  254. """Star argument version of :meth:`apply_async`.
  255. Does not support the extra options enabled by :meth:`apply_async`.
  256. :param \*args: positional arguments passed on to the task.
  257. :param \*\*kwargs: keyword arguments passed on to the task.
  258. :returns :class:`celery.result.AsyncResult`:
  259. """
  260. return self.apply_async(args, kwargs)
  261. @classmethod
  262. def apply_async(self, args=None, kwargs=None, countdown=None,
  263. eta=None, task_id=None, publisher=None, connection=None,
  264. connect_timeout=None, router=None, expires=None, queues=None,
  265. **options):
  266. """Apply tasks asynchronously by sending a message.
  267. :keyword args: The positional arguments to pass on to the
  268. task (a :class:`list` or :class:`tuple`).
  269. :keyword kwargs: The keyword arguments to pass on to the
  270. task (a :class:`dict`)
  271. :keyword countdown: Number of seconds into the future that the
  272. task should execute. Defaults to immediate
  273. delivery (do not confuse with the
  274. `immediate` flag, as they are unrelated).
  275. :keyword eta: A :class:`~datetime.datetime` object describing
  276. the absolute time and date of when the task should
  277. be executed. May not be specified if `countdown`
  278. is also supplied. (Do not confuse this with the
  279. `immediate` flag, as they are unrelated).
  280. :keyword expires: Either a :class:`int`, describing the number of
  281. seconds, or a :class:`~datetime.datetime` object
  282. that describes the absolute time and date of when
  283. the task should expire. The task will not be
  284. executed after the expiration time.
  285. :keyword connection: Re-use existing broker connection instead
  286. of establishing a new one. The `connect_timeout`
  287. argument is not respected if this is set.
  288. :keyword connect_timeout: The timeout in seconds, before we give up
  289. on establishing a connection to the AMQP
  290. server.
  291. :keyword retry: If enabled sending of the task message will be retried
  292. in the event of connection loss or failure. Default
  293. is taken from the :setting:`CELERY_TASK_PUBLISH_RETRY`
  294. setting. Note you need to handle the
  295. publisher/connection manually for this to work.
  296. :keyword retry_policy: Override the retry policy used. See the
  297. :setting:`CELERY_TASK_PUBLISH_RETRY` setting.
  298. :keyword routing_key: The routing key used to route the task to a
  299. worker server. Defaults to the
  300. :attr:`routing_key` attribute.
  301. :keyword exchange: The named exchange to send the task to.
  302. Defaults to the :attr:`exchange` attribute.
  303. :keyword exchange_type: The exchange type to initalize the exchange
  304. if not already declared. Defaults to the
  305. :attr:`exchange_type` attribute.
  306. :keyword immediate: Request immediate delivery. Will raise an
  307. exception if the task cannot be routed to a worker
  308. immediately. (Do not confuse this parameter with
  309. the `countdown` and `eta` settings, as they are
  310. unrelated). Defaults to the :attr:`immediate`
  311. attribute.
  312. :keyword mandatory: Mandatory routing. Raises an exception if
  313. there's no running workers able to take on this
  314. task. Defaults to the :attr:`mandatory`
  315. attribute.
  316. :keyword priority: The task priority, a number between 0 and 9.
  317. Defaults to the :attr:`priority` attribute.
  318. :keyword serializer: A string identifying the default
  319. serialization method to use. Can be `pickle`,
  320. `json`, `yaml`, `msgpack` or any custom
  321. serialization method that has been registered
  322. with :mod:`kombu.serialization.registry`.
  323. Defaults to the :attr:`serializer` attribute.
  324. :keyword compression: A string identifying the compression method
  325. to use. Can be one of ``zlib``, ``bzip2``,
  326. or any custom compression methods registered with
  327. :func:`kombu.compression.register`. Defaults to
  328. the :setting:`CELERY_MESSAGE_COMPRESSION`
  329. setting.
  330. .. note::
  331. If the :setting:`CELERY_ALWAYS_EAGER` setting is set, it will
  332. be replaced by a local :func:`apply` call instead.
  333. """
  334. router = self.app.amqp.Router(queues)
  335. conf = self.app.conf
  336. if conf.CELERY_ALWAYS_EAGER:
  337. return self.apply(args, kwargs, task_id=task_id)
  338. options.setdefault("compression",
  339. conf.CELERY_MESSAGE_COMPRESSION)
  340. options = dict(extract_exec_options(self), **options)
  341. options = router.route(options, self.name, args, kwargs)
  342. exchange = options.get("exchange")
  343. exchange_type = options.get("exchange_type")
  344. expires = expires or self.expires
  345. publish = publisher or self.get_publisher(connection,
  346. exchange=exchange,
  347. exchange_type=exchange_type)
  348. evd = None
  349. if conf.CELERY_SEND_TASK_SENT_EVENT:
  350. evd = self.app.events.Dispatcher(channel=publish.channel,
  351. buffer_while_offline=False)
  352. try:
  353. task_id = publish.delay_task(self.name, args, kwargs,
  354. task_id=task_id,
  355. countdown=countdown,
  356. eta=eta, expires=expires,
  357. event_dispatcher=evd,
  358. **options)
  359. finally:
  360. if not publisher:
  361. publish.close()
  362. publish.connection.close()
  363. return self.AsyncResult(task_id)
  364. @classmethod
  365. def retry(self, args=None, kwargs=None, exc=None, throw=True,
  366. eta=None, countdown=None, max_retries=None, **options):
  367. """Retry the task.
  368. :param args: Positional arguments to retry with.
  369. :param kwargs: Keyword arguments to retry with.
  370. :keyword exc: Optional exception to raise instead of
  371. :exc:`~celery.exceptions.MaxRetriesExceededError`
  372. when the max restart limit has been exceeded.
  373. :keyword countdown: Time in seconds to delay the retry for.
  374. :keyword eta: Explicit time and date to run the retry at
  375. (must be a :class:`~datetime.datetime` instance).
  376. :keyword max_retries: If set, overrides the default retry limit.
  377. :keyword \*\*options: Any extra options to pass on to
  378. meth:`apply_async`.
  379. :keyword throw: If this is :const:`False`, do not raise the
  380. :exc:`~celery.exceptions.RetryTaskError` exception,
  381. that tells the worker to mark the task as being
  382. retried. Note that this means the task will be
  383. marked as failed if the task raises an exception,
  384. or successful if it returns.
  385. :raises celery.exceptions.RetryTaskError: To tell the worker that
  386. the task has been re-sent for retry. This always happens,
  387. unless the `throw` keyword argument has been explicitly set
  388. to :const:`False`, and is considered normal operation.
  389. **Example**
  390. .. code-block:: python
  391. >>> @task
  392. >>> def tweet(auth, message):
  393. ... twitter = Twitter(oauth=auth)
  394. ... try:
  395. ... twitter.post_status_update(message)
  396. ... except twitter.FailWhale, exc:
  397. ... # Retry in 5 minutes.
  398. ... return tweet.retry(countdown=60 * 5, exc=exc)
  399. Although the task will never return above as `retry` raises an
  400. exception to notify the worker, we use `return` in front of the retry
  401. to convey that the rest of the block will not be executed.
  402. """
  403. request = self.request
  404. if max_retries is None:
  405. max_retries = self.max_retries
  406. if args is None:
  407. args = request.args
  408. if kwargs is None:
  409. kwargs = request.kwargs
  410. delivery_info = request.delivery_info
  411. if delivery_info:
  412. options.setdefault("exchange", delivery_info.get("exchange"))
  413. options.setdefault("routing_key", delivery_info.get("routing_key"))
  414. if not eta and countdown is None:
  415. countdown = self.default_retry_delay
  416. options.update({"retries": request.retries + 1,
  417. "task_id": request.id,
  418. "countdown": countdown,
  419. "eta": eta})
  420. if max_retries is not None and options["retries"] > max_retries:
  421. raise exc or self.MaxRetriesExceededError(
  422. "Can't retry %s[%s] args:%s kwargs:%s" % (
  423. self.name, options["task_id"], args, kwargs))
  424. # If task was executed eagerly using apply(),
  425. # then the retry must also be executed eagerly.
  426. if request.is_eager:
  427. return self.apply(args=args, kwargs=kwargs, **options).get()
  428. self.apply_async(args=args, kwargs=kwargs, **options)
  429. if throw:
  430. raise RetryTaskError(
  431. eta and "Retry at %s" % (eta, )
  432. or "Retry in %s secs." % (countdown, ), exc)
  433. @classmethod
  434. def apply(self, args=None, kwargs=None, **options):
  435. """Execute this task locally, by blocking until the task
  436. returns.
  437. :param args: positional arguments passed on to the task.
  438. :param kwargs: keyword arguments passed on to the task.
  439. :keyword throw: Re-raise task exceptions. Defaults to
  440. the :setting:`CELERY_EAGER_PROPAGATES_EXCEPTIONS`
  441. setting.
  442. :rtype :class:`celery.result.EagerResult`:
  443. """
  444. args = args or []
  445. kwargs = kwargs or {}
  446. task_id = options.get("task_id") or gen_unique_id()
  447. retries = options.get("retries", 0)
  448. throw = self.app.either("CELERY_EAGER_PROPAGATES_EXCEPTIONS",
  449. options.pop("throw", None))
  450. # Make sure we get the task instance, not class.
  451. task = tasks[self.name]
  452. request = {"id": task_id,
  453. "retries": retries,
  454. "is_eager": True,
  455. "logfile": options.get("logfile"),
  456. "loglevel": options.get("loglevel", 0),
  457. "delivery_info": {"is_eager": True}}
  458. if self.accept_magic_kwargs:
  459. default_kwargs = {"task_name": task.name,
  460. "task_id": task_id,
  461. "task_retries": retries,
  462. "task_is_eager": True,
  463. "logfile": options.get("logfile"),
  464. "loglevel": options.get("loglevel", 0),
  465. "delivery_info": {"is_eager": True}}
  466. supported_keys = fun_takes_kwargs(task.run, default_kwargs)
  467. extend_with = dict((key, val)
  468. for key, val in default_kwargs.items()
  469. if key in supported_keys)
  470. kwargs.update(extend_with)
  471. trace = TaskTrace(task.name, task_id, args, kwargs,
  472. task=task, request=request, propagate=throw)
  473. retval = trace.execute()
  474. if isinstance(retval, ExceptionInfo):
  475. retval = retval.exception
  476. return EagerResult(task_id, retval, trace.status,
  477. traceback=trace.strtb)
  478. @classmethod
  479. def AsyncResult(self, task_id):
  480. """Get AsyncResult instance for this kind of task.
  481. :param task_id: Task id to get result for.
  482. """
  483. return self.app.AsyncResult(task_id, backend=self.backend,
  484. task_name=self.name)
  485. def update_state(self, task_id=None, state=None, meta=None):
  486. """Update task state.
  487. :param task_id: Id of the task to update.
  488. :param state: New state (:class:`str`).
  489. :param meta: State metadata (:class:`dict`).
  490. """
  491. if task_id is None:
  492. task_id = self.request.id
  493. self.backend.store_result(task_id, meta, state)
  494. def on_retry(self, exc, task_id, args, kwargs, einfo=None):
  495. """Retry handler.
  496. This is run by the worker when the task is to be retried.
  497. :param exc: The exception sent to :meth:`retry`.
  498. :param task_id: Unique id of the retried task.
  499. :param args: Original arguments for the retried task.
  500. :param kwargs: Original keyword arguments for the retried task.
  501. :keyword einfo: :class:`~celery.datastructures.ExceptionInfo`
  502. instance, containing the traceback.
  503. The return value of this handler is ignored.
  504. """
  505. pass
  506. def after_return(self, status, retval, task_id, args,
  507. kwargs, einfo=None):
  508. """Handler called after the task returns.
  509. :param status: Current task state.
  510. :param retval: Task return value/exception.
  511. :param task_id: Unique id of the task.
  512. :param args: Original arguments for the task that failed.
  513. :param kwargs: Original keyword arguments for the task
  514. that failed.
  515. :keyword einfo: :class:`~celery.datastructures.ExceptionInfo`
  516. instance, containing the traceback (if any).
  517. The return value of this handler is ignored.
  518. """
  519. pass
  520. def on_failure(self, exc, task_id, args, kwargs, einfo=None):
  521. """Error handler.
  522. This is run by the worker when the task fails.
  523. :param exc: The exception raised by the task.
  524. :param task_id: Unique id of the failed task.
  525. :param args: Original arguments for the task that failed.
  526. :param kwargs: Original keyword arguments for the task
  527. that failed.
  528. :keyword einfo: :class:`~celery.datastructures.ExceptionInfo`
  529. instance, containing the traceback.
  530. The return value of this handler is ignored.
  531. """
  532. pass
  533. def on_success(self, retval, task_id, args, kwargs):
  534. """Success handler.
  535. Run by the worker if the task executes successfully.
  536. :param retval: The return value of the task.
  537. :param task_id: Unique id of the executed task.
  538. :param args: Original arguments for the executed task.
  539. :param kwargs: Original keyword arguments for the executed task.
  540. The return value of this handler is ignored.
  541. """
  542. pass
  543. def execute(self, request, pool, loglevel, logfile, **kwargs):
  544. """The method the worker calls to execute the task.
  545. :param request: A :class:`~celery.worker.job.TaskRequest`.
  546. :param pool: A task pool.
  547. :param loglevel: Current loglevel.
  548. :param logfile: Name of the currently used logfile.
  549. :keyword consumer: The :class:`~celery.worker.consumer.Consumer`.
  550. """
  551. request.execute_using_pool(pool, loglevel, logfile)
  552. def __repr__(self):
  553. """`repr(task)`"""
  554. return "<@task: %s>" % (self.name, )
  555. @classmethod
  556. def subtask(cls, *args, **kwargs):
  557. """Returns :class:`~celery.task.sets.subtask` object for
  558. this task, wrapping arguments and execution options
  559. for a single task invocation."""
  560. from celery.task.sets import subtask
  561. return subtask(cls, *args, **kwargs)
  562. @property
  563. def __name__(self):
  564. return self.__class__.__name__
  565. Task = current_app.Task
  566. class PeriodicTask(Task):
  567. """A periodic task is a task that behaves like a :manpage:`cron` job.
  568. Results of periodic tasks are not stored by default.
  569. .. attribute:: run_every
  570. *REQUIRED* Defines how often the task is run (its interval),
  571. it can be a :class:`~datetime.timedelta` object, a
  572. :class:`~celery.schedules.crontab` object or an integer
  573. specifying the time in seconds.
  574. .. attribute:: relative
  575. If set to :const:`True`, run times are relative to the time when the
  576. server was started. This was the previous behaviour, periodic tasks
  577. are now scheduled by the clock.
  578. :raises NotImplementedError: if the :attr:`run_every` attribute is
  579. not defined.
  580. Example
  581. >>> from celery.task import tasks, PeriodicTask
  582. >>> from datetime import timedelta
  583. >>> class EveryThirtySecondsTask(PeriodicTask):
  584. ... run_every = timedelta(seconds=30)
  585. ...
  586. ... def run(self, **kwargs):
  587. ... logger = self.get_logger(**kwargs)
  588. ... logger.info("Execute every 30 seconds")
  589. >>> from celery.task import PeriodicTask
  590. >>> from celery.schedules import crontab
  591. >>> class EveryMondayMorningTask(PeriodicTask):
  592. ... run_every = crontab(hour=7, minute=30, day_of_week=1)
  593. ...
  594. ... def run(self, **kwargs):
  595. ... logger = self.get_logger(**kwargs)
  596. ... logger.info("Execute every Monday at 7:30AM.")
  597. >>> class EveryMorningTask(PeriodicTask):
  598. ... run_every = crontab(hours=7, minute=30)
  599. ...
  600. ... def run(self, **kwargs):
  601. ... logger = self.get_logger(**kwargs)
  602. ... logger.info("Execute every day at 7:30AM.")
  603. >>> class EveryQuarterPastTheHourTask(PeriodicTask):
  604. ... run_every = crontab(minute=15)
  605. ...
  606. ... def run(self, **kwargs):
  607. ... logger = self.get_logger(**kwargs)
  608. ... logger.info("Execute every 0:15 past the hour every day.")
  609. """
  610. abstract = True
  611. ignore_result = True
  612. type = "periodic"
  613. relative = False
  614. options = None
  615. def __init__(self):
  616. app = current_app
  617. if not hasattr(self, "run_every"):
  618. raise NotImplementedError(
  619. "Periodic tasks must have a run_every attribute")
  620. self.run_every = maybe_schedule(self.run_every, self.relative)
  621. # For backward compatibility, add the periodic task to the
  622. # configuration schedule instead.
  623. app.conf.CELERYBEAT_SCHEDULE[self.name] = {
  624. "task": self.name,
  625. "schedule": self.run_every,
  626. "args": (),
  627. "kwargs": {},
  628. "options": self.options or {},
  629. "relative": self.relative,
  630. }
  631. super(PeriodicTask, self).__init__()
  632. def timedelta_seconds(self, delta):
  633. """Convert :class:`~datetime.timedelta` to seconds.
  634. Doesn't account for negative timedeltas.
  635. """
  636. return timeutils.timedelta_seconds(delta)
  637. def is_due(self, last_run_at):
  638. """Returns tuple of two items `(is_due, next_time_to_run)`,
  639. where next time to run is in seconds.
  640. See :meth:`celery.schedules.schedule.is_due` for more information.
  641. """
  642. return self.run_every.is_due(last_run_at)
  643. def remaining_estimate(self, last_run_at):
  644. """Returns when the periodic task should run next as a timedelta."""
  645. return self.run_every.remaining_estimate(last_run_at)