base.py 31 KB

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