blob: 94cb90d412e62425167449025d94cd91f368282c [file] [log] [blame]
Austin Schuhbf610b72024-04-04 20:04:55 -07001#include "aos/events/function_scheduler.h"
2
3namespace aos {
4
5FunctionScheduler::FunctionScheduler(aos::EventLoop *event_loop)
6 : event_loop_(event_loop), timer_(event_loop_->AddTimer([this]() {
7 RunFunctions(event_loop_->context().monotonic_event_time);
8 })) {
9 timer_->set_name("function_timer");
10 event_loop_->OnRun(
11 [this]() { RunFunctions(event_loop_->context().monotonic_event_time); });
12}
13
14void FunctionScheduler::ScheduleAt(std::function<void()> &&function,
15 aos::monotonic_clock::time_point time) {
16 functions_.insert(std::make_pair(time, std::move(function)));
17 timer_->Schedule(functions_.begin()->first);
18}
19
20void FunctionScheduler::RunFunctions(aos::monotonic_clock::time_point now) {
21 while (true) {
22 if (functions_.empty()) return;
23 if (functions_.begin()->first > now) {
24 break;
25 }
26 CHECK_EQ(functions_.begin()->first, now);
27
28 functions_.begin()->second();
29 functions_.erase(functions_.begin());
30 }
31 timer_->Schedule(functions_.begin()->first);
32}
33
34} // namespace aos