Open Model Railroad Network (OpenMRN)
Loading...
Searching...
No Matches
LimitTimer.hxx
Go to the documentation of this file.
1
36#ifndef _UTILS_LIMITTIMER_HXX_
37#define _UTILS_LIMITTIMER_HXX_
38
39#include <algorithm>
40
41#include "executor/Timer.hxx"
42
45class LimitTimer : public Timer
46{
47public:
53 LimitTimer(ExecutorBase *ex, uint16_t update_delay_msec, uint8_t max_tokens,
54 std::function<void()> callback)
55 : Timer(ex->active_timers())
56 , updateDelayMsec_(update_delay_msec)
57 , bucket_(std::min(static_cast<uint8_t>(127), max_tokens))
58 , bucketMax_(max_tokens)
59 , needUpdate_(false)
60 , callback_(callback)
61 {
62 HASSERT(callback);
63 }
64
67 {
68 cancel();
69 }
70
76 bool try_take()
77 {
78 if (bucket_ == bucketMax_)
79 {
81 }
82 if (bucket_ > 0)
83 {
84 --bucket_;
85 return true;
86 }
87 else
88 {
89 needUpdate_ = true;
90 return false;
91 }
92 }
93
98 {
99 if (bucket_ > 0)
100 {
101 --bucket_;
102 }
103 }
104
105private:
107 long long timeout() override
108 {
109 ++bucket_;
110 if (needUpdate_)
111 {
112 needUpdate_ = false;
113 callback_();
114 }
115 if (bucket_ >= bucketMax_)
116 {
117 return NONE;
118 }
119 else
120 {
121 return RESTART;
122 }
123 }
124
127
129 uint8_t bucket_ ;
130
132 uint8_t bucketMax_ : 7;
133
135 uint8_t needUpdate_ : 1;
136
138 std::function<void()> callback_;
139};
140
141#endif // _UTILS_LIMITTIMER_HXX_
This class implements an execution of tasks pulled off an input queue.
Definition Executor.hxx:64
This timer takes care of limiting the number of speed updates we send out in a second.
LimitTimer(ExecutorBase *ex, uint16_t update_delay_msec, uint8_t max_tokens, std::function< void()> callback)
Constructor.
uint16_t updateDelayMsec_
cooldown delay in msec
uint8_t bucketMax_
maximum number of tokens in the bucket
void take_no_callback()
Takes one entry from the bucket, and does not give a callback if there is no entry left.
std::function< void()> callback_
callback after cooldown period.
uint8_t needUpdate_
if non-zero, wake up parent when token is available.
long long timeout() override
Callback from the timer infrastructure. Called periodically.
~LimitTimer()
Destructor.
uint8_t bucket_
number of available tokens
bool try_take()
Attempts to take a token out of the bucket.
A timer that can schedule itself to run on an executor at specified times in the future.
Definition Timer.hxx:134
void cancel()
Dangerous, do not call.
Definition Timer.hxx:260
@ RESTART
Restart the timer with existing period.
Definition Timer.hxx:162
@ NONE
Do not restart the timer.
Definition Timer.hxx:161
void start(long long period=-1)
Starts a timer.
Definition Timer.hxx:185
#define HASSERT(x)
Checks that the value of expression x is true, else terminates the current process.
Definition macros.h:138
#define MSEC_TO_NSEC(_msec)
Convert a millisecond value to a nanosecond value.
Definition os.h:268