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

推荐订阅源

OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
人人都是产品经理
人人都是产品经理
IT之家
IT之家
T
The Blog of Author Tim Ferriss
V
V2EX
博客园 - 聂微东
The Cloudflare Blog
Blog — PlanetScale
Blog — PlanetScale
A
About on SuperTechFans
U
Unit 42
Vercel News
Vercel News
L
LangChain Blog
博客园 - 司徒正美
H
Help Net Security
Recent Announcements
Recent Announcements
Recorded Future
Recorded Future
V
Visual Studio Blog
Jina AI
Jina AI
Microsoft Azure Blog
Microsoft Azure Blog
GbyAI
GbyAI
Y
Y Combinator Blog
C
Check Point Blog
博客园 - 三生石上(FineUI控件)
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
J
Java Code Geeks
The Register - Security
The Register - Security
The GitHub Blog
The GitHub Blog
B
Blog RSS Feed
F
Fortinet All Blogs
B
Blog
G
Google Developers Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
云风的 BLOG
云风的 BLOG
爱范儿
爱范儿
MongoDB | Blog
MongoDB | Blog
F
Full Disclosure
有赞技术团队
有赞技术团队
罗磊的独立博客
博客园_首页
MyScale Blog
MyScale Blog
aimingoo的专栏
aimingoo的专栏
Google DeepMind News
Google DeepMind News
M
MIT News - Artificial intelligence
N
Netflix TechBlog - Medium
Engineering at Meta
Engineering at Meta
量子位
I
InfoQ
小众软件
小众软件
P
Proofpoint News Feed

博客园 - 北叶青藤

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