Crate retry [−] [src]
Crate retry provides functionality for retrying an operation until its return value satisfies a specific condition.
Usage
Retry an operation by calling the retry
function, supplying a maximum number of times to try,
the number of milliseconds to wait after each unsuccessful try, a closure that produces a value,
and a closure that takes a reference to that value and returns a boolean indicating the success
or failure of the operation. The function will return a Result
containing either the value
that satisfied the condition or an error indicating that a satisfactory value could not be
produced.
You can also construct a retryable operation incrementally using the Retry
type. Retry::new
takes the same two closures as mutable references, and returns a Retry
value. You can then
call the try
and wait
methods on this value to add a maximum number of tries and a wait
time, respectively. Finally, run the execute
method to produce the Result
.
If a maximum number of tries is not supplied, the operation will be executed infinitely or until success. If a wait time is not supplied, there will be no wait between attempts.
Failures
Retrying will fail when:
- The operation reaches the maximum number of tries without success.
- A value of 0 is supplied for the maximum number of tries. It must be at least 1.
Examples
Imagine an HTTP API with an endpoint that returns 204 No Content while a job is processing, and eventually 200 OK when the job has completed. Retrying until the job is finished would be written:
match retry(10, 500, || api_client.query_job_status(), |response| response.code == 200) { Ok(response) => println!("Job completed with result: {}", response.body), Err(error) => println!("Job completion could not be verified: {}", error), }
This retries the API call up to 10 times, waiting 500 milliseconds after each unsuccessful
attempt. The same result can be achieved by building a Retry
object incrementally:
match Retry::new( &mut || api_client.query_job_status(), &mut |response| response.code == 200 ).try(10).wait(500).execute() { Ok(response) => println!("Job completed with result: {}", response.body), Err(error) => println!("Job completion could not be verified: {}", error), }
Structs
Retry |
Builder object for a retryable operation. |
RetryError |
An error indicating that a retry call failed. |
Functions
retry |
Invokes a function a certain number of times or until a condition is satisfied with a fixed wait after each unsuccessful try. |