base.py 31 KB

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