|
| 1 | +#ifndef PRE_RETRY_FOR_HPP |
| 2 | +#define PRE_RETRY_FOR_HPP |
| 3 | + |
| 4 | +#include <cassert> |
| 5 | +#include <functional> |
| 6 | +#include <chrono> |
| 7 | +#include <thread> |
| 8 | + |
| 9 | +namespace pre { |
| 10 | + |
| 11 | + |
| 12 | + inline namespace retry_v1 { |
| 13 | + |
| 14 | + /** |
| 15 | + * \brief Sometimes you need to retry some operations, as it's normal that they may fail. |
| 16 | + * Typically an IO error is not always a real error, as the media may |
| 17 | + * be known to be instable (e.g. airwaves communication, speaking over |
| 18 | + * serial line when remote device is busy...) |
| 19 | + * |
| 20 | + * Typically if there are many retries tried out without any pause in between, the |
| 21 | + * operation may still fail, as the main reason for something not to reply is to be |
| 22 | + * busy. Therefore this function allows you to specify blackout time as well as a |
| 23 | + * complete retry time. |
| 24 | + * |
| 25 | + * **Preconditions**: blackout_step must be a multiple of total_time. |
| 26 | + * |
| 27 | + * \param total_time Total time allowed for retrying. |
| 28 | + * \param time_step Wait time between retries. |
| 29 | + * \param retried_func Callback retried returning true on success, false on error. |
| 30 | + * |
| 31 | + * \return Whether the callback succeeded or not. |
| 32 | + */ |
| 33 | + template< class Rep, class Period > |
| 34 | + inline bool retry_for( |
| 35 | + const std::chrono::duration<Rep, Period>& total_time, |
| 36 | + const std::chrono::duration<Rep, Period>& time_step, |
| 37 | + std::function<bool (void)> retried_func) { |
| 38 | + assert(time_step.count()!=0); |
| 39 | + assert(total_time.count() >= time_step.count()); |
| 40 | + |
| 41 | + size_t iterations = total_time.count() / time_step.count(); |
| 42 | + for(size_t p=0; p <iterations; p++) { |
| 43 | + if(retried_func()) { return true; } |
| 44 | + std::this_thread::sleep_for(time_step); |
| 45 | + } |
| 46 | + return false; |
| 47 | + } |
| 48 | + |
| 49 | + /** |
| 50 | + * \brief Equivalent to : |
| 51 | + * sleep_for(initial_blackout); pre::retry_for(total_time, time_step, retried_func); |
| 52 | + * |
| 53 | + * Please see [pre::retry_for](@ref pre::retry_for(const std::chrono::duration<Rep, Period>&, |
| 54 | + * const std::chrono::duration<Rep, Period>& , std::function<bool (void)>)). |
| 55 | + */ |
| 56 | + template< class Rep, class Period > |
| 57 | + inline bool retry_for( |
| 58 | + const std::chrono::duration<Rep, Period>& total_time, |
| 59 | + const std::chrono::duration<Rep, Period>& time_step, |
| 60 | + const std::chrono::duration<Rep, Period>& initial_blackout, |
| 61 | + std::function<bool (void)> retried_func) { |
| 62 | + std::this_thread::sleep_for(initial_blackout); |
| 63 | + return retry_for(total_time, time_step, retried_func); |
| 64 | + } |
| 65 | + |
| 66 | + } |
| 67 | + |
| 68 | +} |
| 69 | + |
| 70 | +#endif |
0 commit comments