File tree Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Original file line number Diff line number Diff line change @@ -468,6 +468,27 @@ struct TypeTraits<WallTime> {
468
468
}
469
469
};
470
470
471
+ // / Throttles the invocation of a callable to not exceed a specified rate.
472
+ // / The rate is controlled by a cooldown interval.
473
+ class ThrottledInvoker {
474
+ public:
475
+ explicit ThrottledInvoker (Seconds cooldown_interval)
476
+ : cooldown_interval_(cooldown_interval) {}
477
+
478
+ template <typename Callable>
479
+ void operator ()(MonoTime now, Callable&& callable)
480
+ {
481
+ if (duration_cast<Seconds>(now - last_time_invoked_) >= cooldown_interval_) {
482
+ last_time_invoked_ = now;
483
+ std::forward<Callable>(callable)();
484
+ }
485
+ }
486
+
487
+ private:
488
+ const Seconds cooldown_interval_{};
489
+ MonoTime last_time_invoked_{};
490
+ };
491
+
471
492
} // namespace util
472
493
} // namespace toolbox
473
494
Original file line number Diff line number Diff line change @@ -124,4 +124,31 @@ BOOST_AUTO_TEST_CASE(PutTimeOutput2)
124
124
BOOST_CHECK_EQUAL (stream.str (), " 20180824T05:32:29.001001001" );
125
125
}
126
126
127
+ BOOST_AUTO_TEST_CASE (ThrottledInvokerCheck)
128
+ {
129
+ constexpr auto threshold = 1s;
130
+ ThrottledInvoker throttler{threshold};
131
+
132
+ std::size_t count = 0 ;
133
+ auto now = MonoClock::now ();
134
+
135
+ auto check_throttling = [&] {
136
+ const auto end = now + threshold;
137
+ while (now <= end) {
138
+ throttler (now, [&]() { ++count; });
139
+ now = MonoClock::now ();
140
+ }
141
+ };
142
+
143
+ check_throttling ();
144
+ BOOST_CHECK_EQUAL (count, 1 );
145
+
146
+ now = MonoClock::now () + threshold;
147
+
148
+ // the throttle should invoke again now
149
+ check_throttling ();
150
+ BOOST_CHECK_EQUAL (count, 2 );
151
+ }
152
+
153
+
127
154
BOOST_AUTO_TEST_SUITE_END ()
You can’t perform that action at this time.
0 commit comments