Skip to content

Commit 7bcc990

Browse files
committed
feat: Add ThrottledInvoker utility
Common use case is throttling logging. SDB-9889
1 parent ff08d4f commit 7bcc990

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

toolbox/sys/Time.hpp

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -468,6 +468,27 @@ struct TypeTraits<WallTime> {
468468
}
469469
};
470470

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+
471492
} // namespace util
472493
} // namespace toolbox
473494

toolbox/sys/Time.ut.cpp

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,4 +124,31 @@ BOOST_AUTO_TEST_CASE(PutTimeOutput2)
124124
BOOST_CHECK_EQUAL(stream.str(), "20180824T05:32:29.001001001");
125125
}
126126

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+
127154
BOOST_AUTO_TEST_SUITE_END()

0 commit comments

Comments
 (0)