rust-tokio-retry
rust-tokio-retry copied to clipboard
Please include an example of retrying something other than a function taking no parameters
I have an async operation that I'd like to retry that requires input parameters. Async closures are unstable, and an async block returns a dyn Future, not an FnMut(). Implementing Action directly is difficult because I have to name the type implementing Future returned by my method. Is it possible to use this crate on stable if my operation requires parameters? If so, how?
Something like this should work:
use tokio_retry::Retry;
use tokio_retry::strategy::{ExponentialBackoff, jitter};
async fn action(url: &str) -> Result<u64, ()> {
// do some real-world stuff here...
Err(())
}
#[tokio::main]
async fn main() -> Result<(), ()> {
let retry_strategy = ExponentialBackoff::from_millis(10)
.map(jitter) // add jitter to delays
.take(3); // limit to 3 retries
let url = "http://example.com";
let result = Retry::spawn(retry_strategy, || action(&url) ).await?;
Ok(())
}