惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Visual Studio Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
N
Netflix TechBlog - Medium
博客园 - 叶小钗
大猫的无限游戏
大猫的无限游戏
S
SegmentFault 最新的问题
V
V2EX
IT之家
IT之家
J
Java Code Geeks
Hacker News - Newest:
Hacker News - Newest: "LLM"
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
GbyAI
GbyAI
D
Docker
S
Secure Thoughts
Recent Announcements
Recent Announcements
Webroot Blog
Webroot Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
云风的 BLOG
云风的 BLOG
博客园_首页
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Security Archives - TechRepublic
Security Archives - TechRepublic
酷 壳 – CoolShell
酷 壳 – CoolShell
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
N
News | PayPal Newsroom
S
Security @ Cisco Blogs
I
InfoQ
Last Week in AI
Last Week in AI
SecWiki News
SecWiki News
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
W
WeLiveSecurity
T
Troy Hunt's Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Attack and Defense Labs
Attack and Defense Labs
美团技术团队
T
The Blog of Author Tim Ferriss
Google DeepMind News
Google DeepMind News
Martin Fowler
Martin Fowler
B
Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Scott Helme
Scott Helme
T
Tor Project blog
Know Your Adversary
Know Your Adversary
有赞技术团队
有赞技术团队
Hugging Face - Blog
Hugging Face - Blog
Recorded Future
Recorded Future
C
Cyber Attacks, Cyber Crime and Cyber Security
AI
AI
G
Google Developers Blog

博客园 - 北叶青藤

2096. Step-By-Step Directions From a Binary Tree Node to Another Find path from root to a target node in Binary Tree When Dijkstra Algorithm Should be Use? 1188. Design Bounded Blocking Queue 1115. Print FooBar Alternately 1114. Print in Order 1242. Web Crawler Multithreaded Python Multi-threading bot ip Log Rate Limiter Same Word of HTML Labels Most Frequent Call Chain remove prefix in a words list 1102. Path With Maximum Minimum Value Property Booking Optimizer minimum number 755. Pour Water Keyword Tagging in Reviews with Overlapping Matches 1125. Smallest Sufficient Team Print the terrain Split stay Task scheduling problem 滑雪问题 845. Longest Mountain in Array 723. Candy Crush 1539. Kth Missing Positive Number 1650. Lowest Common Ancestor of a Binary Tree III 424. Longest Repeating Character Replacement 843. Guess the Word 551. Student Attendance Record I
Retryer Function Implementation
北叶青藤 · 2026-02-25 · via 博客园 - 北叶青藤

Design a retryer function that takes an asynchronous function and a maximum number of retries. The retry delay should grow exponentially (e.g., 2 seconds, 4 seconds, 8 seconds, etc.). If the asynchronous function succeeds within the maximum retries, return the result; if it fails after the maximum retries, throw an error.

Input

  • func: an asynchronous function to retry, with no parameters.
  • max_retries: an integer specifying the maximum number of retries.

Output

  • Returns the result of the asynchronous function or throws an error.

Example

async def my_async_function():
    # Simulate a potentially failing async call

result = await retryer(my_async_function, 3)

Constraints

  • Assume each call to the async function is independent and has no global state.
  • Exponential backoff should wait for a maximum of 16 seconds, use await asyncio.sleep() to simulate wait time.
 1 import asyncio
 2 from typing import Callable, Awaitable, TypeVar
 3 
 4 T = TypeVar("T")
 5 
 6 async def retryer(
 7     func: Callable[[], Awaitable[T]],
 8     max_retries: int
 9 ) -> T:
10     """
11     Retry an async function with exponential backoff.
12 
13     :param func: async function with no parameters
14     :param max_retries: maximum number of retries (after first attempt)
15     :return: result of func()
16     :raises: last exception if all attempts fail
17     """
18     if max_retries < 0:
19         raise ValueError("max_retries must be >= 0")
20 
21     attempt = 0
22     delay = 2  # initial delay in seconds
23     max_delay = 16
24 
25     while True:
26         try:
27             return await func()
28         except Exception as e:
29             if attempt >= max_retries:
30                 raise e
31 
32             await asyncio.sleep(delay)
33 
34             delay = min(delay * 2, max_delay)
35             attempt += 1

or

 1 async def retryer(func, max_retries):
 2     delay = 2
 3     max_delay = 16
 4 
 5     for attempt in range(max_retries + 1):
 6         try:
 7             return await func()
 8         except Exception as e:
 9             if attempt == max_retries:
10                 raise e
11             await asyncio.sleep(delay)
12             delay = min(delay * 2, max_delay)

Test Case

 1 import random
 2 import asyncio
 3 
 4 async def my_async_function():
 5     if random.random() < 0.7:
 6         raise ValueError("Random failure")
 7     return "Success!"
 8 
 9 async def main():
10     try:
11         result = await retryer(my_async_function, 3)
12         print("Result:", result)
13     except Exception as e:
14         print("Final failure:", e)
15 
16 asyncio.run(main())