Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 1 | #include "aos/events/event_scheduler.h" |
| 2 | |
| 3 | #include <algorithm> |
| 4 | #include <deque> |
| 5 | |
| 6 | #include "aos/events/event_loop.h" |
| 7 | |
| 8 | namespace aos { |
| 9 | |
| 10 | EventScheduler::Token EventScheduler::Schedule( |
| 11 | ::aos::monotonic_clock::time_point time, ::std::function<void()> callback) { |
| 12 | return events_list_.emplace(time, callback); |
| 13 | } |
| 14 | |
| 15 | void EventScheduler::Deschedule(EventScheduler::Token token) { |
| 16 | events_list_.erase(token); |
| 17 | } |
| 18 | |
| 19 | void EventScheduler::RunFor(monotonic_clock::duration duration) { |
| 20 | const ::aos::monotonic_clock::time_point end_time = |
| 21 | monotonic_now() + duration; |
| 22 | is_running_ = true; |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 23 | for (std::function<void()> &on_run : on_run_) { |
| 24 | on_run(); |
| 25 | } |
| 26 | on_run_.clear(); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 27 | while (!events_list_.empty() && is_running_) { |
| 28 | auto iter = events_list_.begin(); |
| 29 | ::aos::monotonic_clock::time_point next_time = iter->first; |
| 30 | if (next_time > end_time) { |
| 31 | break; |
| 32 | } |
| 33 | now_ = iter->first; |
| 34 | ::std::function<void()> callback = ::std::move(iter->second); |
| 35 | events_list_.erase(iter); |
| 36 | callback(); |
| 37 | } |
| 38 | now_ = end_time; |
| 39 | } |
| 40 | |
| 41 | void EventScheduler::Run() { |
| 42 | is_running_ = true; |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 43 | for (std::function<void()> &on_run : on_run_) { |
| 44 | on_run(); |
| 45 | } |
| 46 | on_run_.clear(); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 47 | while (!events_list_.empty() && is_running_) { |
| 48 | auto iter = events_list_.begin(); |
| 49 | now_ = iter->first; |
| 50 | ::std::function<void()> callback = ::std::move(iter->second); |
| 51 | events_list_.erase(iter); |
| 52 | callback(); |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | } // namespace aos |