base.py 31 KB

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