QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
ExponentialBackoff.h
Go to the documentation of this file.
1#pragma once
2
3#include <algorithm>
4#include <chrono>
5
8{
9public:
10 using Delay = std::chrono::milliseconds;
11
13 constexpr ExponentialBackoff(Delay initial, double factor, Delay cap, Delay maxRetryAfter = Delay::zero())
14 : _initial(initial)
15 , _factor(factor)
16 , _cap(cap)
17 , _maxRetryAfter(maxRetryAfter)
18 , _delay(initial)
19 {}
20
23 constexpr Delay peek(Delay retryAfter = Delay::zero()) const
24 {
25 return std::clamp(retryAfter, _delay, (std::max) (_delay, _maxRetryAfter));
26 }
27
29 constexpr Delay next(Delay retryAfter = Delay::zero())
30 {
31 const Delay delay = peek(retryAfter);
32 const auto grown = _delay * _factor;
33 _delay = grown < _cap ? std::chrono::duration_cast<Delay>(grown) : _cap;
34 ++_attempts;
35 return delay;
36 }
37
38 constexpr void reset()
39 {
40 _delay = _initial;
41 _attempts = 0;
42 }
43
45 constexpr int attempts() const { return _attempts; }
46
47private:
48 Delay _initial;
49 double _factor;
50 Delay _cap;
51 Delay _maxRetryAfter;
52 Delay _delay;
53 int _attempts = 0;
54};
Retry delays that start at an initial value and grow by a factor per attempt, up to a cap.
constexpr int attempts() const
Attempts counted since construction or the last reset().
std::chrono::milliseconds Delay
constexpr Delay peek(Delay retryAfter=Delay::zero()) const
constexpr Delay next(Delay retryAfter=Delay::zero())
Returns peek(retryAfter) and counts the attempt.
constexpr ExponentialBackoff(Delay initial, double factor, Delay cap, Delay maxRetryAfter=Delay::zero())
A positive maxRetryAfter lets a server's retry-after hint lengthen a delay, up to that limit.
constexpr void reset()