Пример #1
0
    def retry(self, args=None, kwargs=None, exc=None, throw=True,
              eta=None, countdown=None, max_retries=None, **options):
        """Retry the task.

        Example:
            >>> from imaginary_twitter_lib import Twitter
            >>> from proj.celery import app

            >>> @app.task(bind=True)
            ... def tweet(self, auth, message):
            ...     twitter = Twitter(oauth=auth)
            ...     try:
            ...         twitter.post_status_update(message)
            ...     except twitter.FailWhale as exc:
            ...         # Retry in 5 minutes.
            ...         raise self.retry(countdown=60 * 5, exc=exc)

        Note:
            Although the task will never return above as `retry` raises an
            exception to notify the worker, we use `raise` in front of the
            retry to convey that the rest of the block won't be executed.

        Arguments:
            args (Tuple): Positional arguments to retry with.
            kwargs (Dict): Keyword arguments to retry with.
            exc (Exception): Custom exception to report when the max restart
                limit has been exceeded (default:
                :exc:`~@MaxRetriesExceededError`).

                If this argument is set and retry is called while
                an exception was raised (``sys.exc_info()`` is set)
                it will attempt to re-raise the current exception.

                If no exception was raised it will raise the ``exc``
                argument provided.
            countdown (float): Time in seconds to delay the retry for.
            eta (~datetime.dateime): Explicit time and date to run the
                retry at.
            max_retries (int): If set, overrides the default retry limit for
                this execution.  Changes to this parameter don't propagate to
                subsequent task retry attempts.  A value of :const:`None`,
                means "use the default", so if you want infinite retries you'd
                have to set the :attr:`max_retries` attribute of the task to
                :const:`None` first.
            time_limit (int): If set, overrides the default time limit.
            soft_time_limit (int): If set, overrides the default soft
                time limit.
            throw (bool): If this is :const:`False`, don't raise the
                :exc:`~@Retry` exception, that tells the worker to mark
                the task as being retried.  Note that this means the task
                will be marked as failed if the task raises an exception,
                or successful if it returns after the retry call.
            **options (Any): Extra options to pass on to :meth:`apply_async`.

        Raises:
            celery.exceptions.Retry:
                To tell the worker that the task has been re-sent for retry.
                This always happens, unless the `throw` keyword argument
                has been explicitly set to :const:`False`, and is considered
                normal operation.
        """
        request = self.request
        retries = request.retries + 1
        max_retries = self.max_retries if max_retries is None else max_retries

        # Not in worker or emulated by (apply/always_eager),
        # so just raise the original exception.
        if request.called_directly:
            # raises orig stack if PyErr_Occurred,
            # and augments with exc' if that argument is defined.
            raise_with_context(exc or Retry('Task can be retried', None))

        if not eta and countdown is None:
            countdown = self.default_retry_delay

        is_eager = request.is_eager
        S = self.signature_from_request(
            request, args, kwargs,
            countdown=countdown, eta=eta, retries=retries,
            **options
        )

        if max_retries is not None and retries > max_retries:
            if exc:
                # On Py3: will augment any current exception with
                # the exc' argument provided (raise exc from orig)
                raise_with_context(exc)
            raise self.MaxRetriesExceededError(
                "Can't retry {0}[{1}] args:{2} kwargs:{3}".format(
                    self.name, request.id, S.args, S.kwargs))

        ret = Retry(exc=exc, when=eta or countdown)

        if is_eager:
            # if task was executed eagerly using apply(),
            # then the retry must also be executed eagerly.
            S.apply().get()
            if throw:
                raise ret
            return ret

        try:
            S.apply_async()
        except Exception as exc:
            raise Reject(exc, requeue=False)
        if throw:
            raise ret
        return ret
Пример #2
0
    def retry(self,
              args=None,
              kwargs=None,
              exc=None,
              throw=True,
              eta=None,
              countdown=None,
              max_retries=None,
              **options):
        """Retry the task, adding it to the back of the queue.

        Example:
            >>> from imaginary_twitter_lib import Twitter
            >>> from proj.celery import app

            >>> @app.task(bind=True)
            ... def tweet(self, auth, message):
            ...     twitter = Twitter(oauth=auth)
            ...     try:
            ...         twitter.post_status_update(message)
            ...     except twitter.FailWhale as exc:
            ...         # Retry in 5 minutes.
            ...         raise self.retry(countdown=60 * 5, exc=exc)

        Note:
            Although the task will never return above as `retry` raises an
            exception to notify the worker, we use `raise` in front of the
            retry to convey that the rest of the block won't be executed.

        Arguments:
            args (Tuple): Positional arguments to retry with.
            kwargs (Dict): Keyword arguments to retry with.
            exc (Exception): Custom exception to report when the max retry
                limit has been exceeded (default:
                :exc:`~@MaxRetriesExceededError`).

                If this argument is set and retry is called while
                an exception was raised (``sys.exc_info()`` is set)
                it will attempt to re-raise the current exception.

                If no exception was raised it will raise the ``exc``
                argument provided.
            countdown (float): Time in seconds to delay the retry for.
            eta (~datetime.datetime): Explicit time and date to run the
                retry at.
            max_retries (int): If set, overrides the default retry limit for
                this execution.  Changes to this parameter don't propagate to
                subsequent task retry attempts.  A value of :const:`None`,
                means "use the default", so if you want infinite retries you'd
                have to set the :attr:`max_retries` attribute of the task to
                :const:`None` first.
            time_limit (int): If set, overrides the default time limit.
            soft_time_limit (int): If set, overrides the default soft
                time limit.
            throw (bool): If this is :const:`False`, don't raise the
                :exc:`~@Retry` exception, that tells the worker to mark
                the task as being retried.  Note that this means the task
                will be marked as failed if the task raises an exception,
                or successful if it returns after the retry call.
            **options (Any): Extra options to pass on to :meth:`apply_async`.

        Raises:
            celery.exceptions.Retry:
                To tell the worker that the task has been re-sent for retry.
                This always happens, unless the `throw` keyword argument
                has been explicitly set to :const:`False`, and is considered
                normal operation.
        """
        request = self.request
        retries = request.retries + 1
        max_retries = self.max_retries if max_retries is None else max_retries

        # Not in worker or emulated by (apply/always_eager),
        # so just raise the original exception.
        if request.called_directly:
            # raises orig stack if PyErr_Occurred,
            # and augments with exc' if that argument is defined.
            raise_with_context(exc or Retry('Task can be retried', None))

        if not eta and countdown is None:
            countdown = self.default_retry_delay

        is_eager = request.is_eager
        S = self.signature_from_request(request,
                                        args,
                                        kwargs,
                                        countdown=countdown,
                                        eta=eta,
                                        retries=retries,
                                        **options)

        if max_retries is not None and retries > max_retries:
            if exc:
                # On Py3: will augment any current exception with
                # the exc' argument provided (raise exc from orig)
                raise_with_context(exc)
            raise self.MaxRetriesExceededError(
                "Can't retry {0}[{1}] args:{2} kwargs:{3}".format(
                    self.name, request.id, S.args, S.kwargs),
                task_args=S.args,
                task_kwargs=S.kwargs)

        ret = Retry(exc=exc, when=eta or countdown)

        if is_eager:
            # if task was executed eagerly using apply(),
            # then the retry must also be executed eagerly.
            S.apply().get(disable_sync_subtasks=False)
            if throw:
                raise ret
            return ret

        try:
            S.apply_async()
        except Exception as exc:
            raise Reject(exc, requeue=False)
        if throw:
            raise ret
        return ret