✨ more retries
This commit is contained in:
parent
46cb21dc2a
commit
4e49080958
1 changed files with 42 additions and 0 deletions
42
src/lib.rs
42
src/lib.rs
|
@ -76,6 +76,48 @@ pub fn retry<O, F: Fn() -> Option<O>>(f: F) -> O {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn retry_max<O, F: Fn() -> Option<O>>(max: u64, f: F) -> Option<O> {
|
||||
let mut counter = 0;
|
||||
while counter < max {
|
||||
match f() {
|
||||
Some(resp) => {
|
||||
return Some(resp);
|
||||
}
|
||||
None => {
|
||||
log::info!("Got nothing, retrying {}/{}", counter + 1, max);
|
||||
}
|
||||
}
|
||||
counter += 1;
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// Retries a function gracefully with exponential backoff.
|
||||
///
|
||||
/// - `f`: A function that returns an `Option<O>`, retried on `None`.
|
||||
/// - Starts with `base_delay` and doubles it each attempt, capping at `max_delay`.
|
||||
///
|
||||
/// Returns `Some(O)` if successful, otherwise keeps retrying indefinitely.
|
||||
pub fn retry_backoff<O, F: Fn() -> Option<O>>(
|
||||
f: F,
|
||||
base_delay: Duration,
|
||||
max_delay: Duration,
|
||||
) -> Option<O> {
|
||||
let mut delay = base_delay;
|
||||
|
||||
loop {
|
||||
match f() {
|
||||
Some(resp) => return Some(resp),
|
||||
None => {
|
||||
log::info!("Got nothing, retrying in {:?}", delay);
|
||||
thread::sleep(delay);
|
||||
delay = (delay * 2).min(max_delay);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Run a background task.
|
||||
///
|
||||
/// This spawns a seperate thread for a background process.
|
||||
|
|
Loading…
Add table
Reference in a new issue