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

推荐订阅源

Jina AI
Jina AI
T
The Blog of Author Tim Ferriss
B
Blog
L
LangChain Blog
Y
Y Combinator Blog
美团技术团队
博客园 - 三生石上(FineUI控件)
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
G
Google Developers Blog
量子位
博客园_首页
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
C
Check Point Blog
D
Docker
小众软件
小众软件
The Cloudflare Blog
大猫的无限游戏
大猫的无限游戏
T
Tailwind CSS Blog
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 聂微东
Blog — PlanetScale
Blog — PlanetScale
GbyAI
GbyAI
Google DeepMind News
Google DeepMind News
IT之家
IT之家

博客园 - 北叶青藤

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())