|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +""" |
| 4 | +@author: 闲欢 |
| 5 | +""" |
| 6 | +import random |
| 7 | +from retrying import retry |
| 8 | + |
| 9 | + |
| 10 | +@retry |
| 11 | +def do_something_unreliable(): |
| 12 | + if random.randint(0, 10) > 1: |
| 13 | + print("just have a test") |
| 14 | + raise IOError("raise exception!") |
| 15 | + else: |
| 16 | + return "good job!" |
| 17 | + |
| 18 | + |
| 19 | +print(do_something_unreliable()) |
| 20 | + |
| 21 | + |
| 22 | +# 最大重试次数 |
| 23 | +@retry(stop_max_attempt_number=5) |
| 24 | +def do_something_limited(): |
| 25 | + print("do something several times") |
| 26 | + raise Exception("raise exception") |
| 27 | + |
| 28 | +# do_something_limited() |
| 29 | + |
| 30 | + |
| 31 | +# 限制最长重试时间(从执行方法开始计算) |
| 32 | +@retry(stop_max_delay=5000) |
| 33 | +def do_something_in_time(): |
| 34 | + print("do something in time") |
| 35 | + raise Exception("raise exception") |
| 36 | + |
| 37 | +# do_something_in_time() |
| 38 | + |
| 39 | + |
| 40 | +# 设置固定重试时间 |
| 41 | +@retry(wait_fixed=2000) |
| 42 | +def wait_fixed_time(): |
| 43 | + print("wait") |
| 44 | + raise Exception("raise exception") |
| 45 | + |
| 46 | +# wait_fixed_time() |
| 47 | + |
| 48 | +# 设置重试时间的随机范围 |
| 49 | +@retry(wait_random_min=1000,wait_random_max=2000) |
| 50 | +def wait_random_time(): |
| 51 | + print("wait") |
| 52 | + raise Exception("raise exception") |
| 53 | + |
| 54 | +# wait_random_time() |
| 55 | + |
| 56 | + |
| 57 | +# 根据异常重试 |
| 58 | +def retry_if_io_error(exception): |
| 59 | + return isinstance(exception, IOError) |
| 60 | + |
| 61 | +# 设置特定异常类型重试 |
| 62 | +@retry(retry_on_exception=retry_if_io_error) |
| 63 | +def retry_special_error(): |
| 64 | + print("retry io error") |
| 65 | + raise IOError("raise exception") |
| 66 | + |
| 67 | +# retry_special_error() |
| 68 | + |
| 69 | + |
| 70 | +# 通过返回值判断是否重试 |
| 71 | +def retry_if_result_none(result): |
| 72 | + """Return True if we should retry (in this case when result is None), False otherwise""" |
| 73 | + # return result is None |
| 74 | + if result =="111": |
| 75 | + return True |
| 76 | + |
| 77 | + |
| 78 | +@retry(retry_on_result=retry_if_result_none) |
| 79 | +def might_return_none(): |
| 80 | + print("Retry forever ignoring Exceptions with no wait if return value is None") |
| 81 | + return "111" |
| 82 | + |
| 83 | +might_return_none() |
| 84 | + |
| 85 | + |
| 86 | + |
| 87 | + |
| 88 | + |
| 89 | + |
| 90 | + |
0 commit comments