https://github.com/leshow/retry_fn
retry executing a closure or future on a timer
https://github.com/leshow/retry_fn
Last synced: about 1 year ago
JSON representation
retry executing a closure or future on a timer
- Host: GitHub
- URL: https://github.com/leshow/retry_fn
- Owner: leshow
- License: mit
- Created: 2020-11-13T21:22:14.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2024-09-12T21:56:51.000Z (almost 2 years ago)
- Last Synced: 2025-04-02T02:46:25.876Z (over 1 year ago)
- Language: Rust
- Size: 59.6 KB
- Stars: 6
- Watchers: 0
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# retry_fn
[](https://github.com/leshow/retry_fn/actions)
[](https://crates.io/crates/retry_fn)
[](https://docs.rs/retry_fn)
Function for executing retry either as a closure with a std-based sleep (`thread::sleep`) or
using either of the most popular async runtime's. Tokio or async-std. Inspired by the other
retry libraries out there, the desire is to keep this up-to-date and combine features from several.
## Sync Example
```rust
use std::{io, time::Duration};
use retry_fn::{retry, strategy::ExponentialBackoff, RetryResult};
fn main() -> Result<(), Box> {
let mut count = 0;
let res = retry(ExponentialBackoff::new(Duration::from_secs(2)), |op| {
if op.retries >= 3 {
RetryResult::<&str, _>::Err(io::Error::new(
io::ErrorKind::TimedOut,
"timed out",
))
} else {
count += 1;
RetryResult::Retry()
}
});
assert_eq!(count, 3);
assert!(res.is_err());
Ok(())
}
```
## Using tokio
Enable the `tokio-runtime` feature to get access to this function
```rust
use std::{io, sync::{Arc, Mutex}};
use retry_fn::{tokio::retry, strategy::Constant, RetryResult};
#[tokio::main]
async fn main() -> Result<(), Box> {
let count: Arc> = Arc::new(Mutex::new(0));
let res = retry(Constant::from_millis(100), |op| {
let count = count.clone();
async move {
if op.retries >= 3 {
RetryResult::<&str, _>::Err(io::Error::new(
io::ErrorKind::TimedOut,
"timed out",
))
} else {
*count.lock().unwrap() += 1;
RetryResult::Retry()
}
}
})
.await;
assert_eq!(*count.lock().unwrap(), 3);
assert!(res.is_err());
Ok(())
}
```