base.py 32 KB

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