# retry

## 1 功能

* 函数可以根据以下条件重试:
  * 执行结果是否成功 (like a status code not equaling 200)
  * Exceptions (like a function raising a requests.RequestException)
    * 所有接受的异常也会在失败时引发原始异常！
* 函数执行失败可能是:
  * 超过最大重试次数
  * 达到最大超时时间
* 函数重试可以按特定的间隔间隔进行

## 2 例子

### 2.1 简单例子

```
from xlib.util import retry

print "------------------------------------------func"
@retry.retry(max_retries=3, interval=5)
def add(a, b):
    return a + b


print add(3, 5)

print "------------------------------------------class"
class Demo():
    @retry.retry(max_retries=3, interval=5)
    def add(self, a, b):
        assert a == 4
        return a + b

demo = Demo()
print demo.add(3, 5)
```

### 2.2 装饰器

Send a `GET` request to a URL until it returns a status code of 200!

> 每秒重试一次

```python
import requests

from xlib.util import retry

@retry.retry(max_retries=-1, interval=1, success=lambda x: x.status_code == 200)
def poll_url(url, method='GET'):
    return requests.request(method, url)
```

### 2.3 添加超时时间

Same function as above, timeout after 10 seconds!

```python
import requests

from xlib.util import retry

@retry.retry(max_retries=-1, interval=1, success=lambda x: x.status_code == 200, timeout=10)
def poll_url(url, method='GET'):
    return requests.request(method, url)
```

### 2.4 添加 exceptions 参数

Same function as above, timeout after 10 seconds!

```python
import requests

from xlib.util import retry

@retry.retry(
    exceptions=(requests.RequestException,), max_retries=-1, interval=1,
    success=lambda x: x.status_code == 200, timeout=10)
def poll_url(url, method='GET'):
    return requests.request(method, url)
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://meetbill.gitbook.io/butterfly-user-doc/tools/decorator/retry_decorator.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
