base.py 31 KB

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