Austin Schuh | bf610b7 | 2024-04-04 20:04:55 -0700 | [diff] [blame] | 1 | #include "aos/events/function_scheduler.h" |
| 2 | |
| 3 | namespace aos { |
| 4 | |
| 5 | FunctionScheduler::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 | |
| 14 | void 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 | |
| 20 | void 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 |