rust-tokio-retry icon indicating copy to clipboard operation
rust-tokio-retry copied to clipboard

Please include an example of retrying something other than a function taking no parameters

Open sp1ff opened this issue 2 years ago • 1 comments

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?

sp1ff avatar Aug 11 '22 14:08 sp1ff

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

awnion avatar Aug 20 '22 19:08 awnion