blob: 432f4ad0dc0c0668d356f348640b015e71d3299a [file] [log] [blame]
Alex Perrycb7da4b2019-08-28 19:35:56 -07001#ifndef AOS_EVENTS_EVENT_SCHEDULER_H_
2#define AOS_EVENTS_EVENT_SCHEDULER_H_
3
4#include <algorithm>
5#include <map>
6#include <memory>
7#include <unordered_set>
8#include <utility>
9#include <vector>
10
11#include "aos/events/event_loop.h"
12#include "aos/time/time.h"
13#include "glog/logging.h"
14
15namespace aos {
16
17class EventScheduler {
18 public:
19 using ChannelType =
20 std::multimap<monotonic_clock::time_point, std::function<void()>>;
21 using Token = ChannelType::iterator;
22
23 // Schedule an event with a callback function
24 // Returns an iterator to the event
25 Token Schedule(monotonic_clock::time_point time,
26 std::function<void()> callback);
27
Austin Schuh39788ff2019-12-01 18:22:57 -080028 // Schedules a callback when the event scheduler starts.
29 void ScheduleOnRun(std::function<void()> callback) {
30 on_run_.emplace_back(std::move(callback));
31 }
32
Alex Perrycb7da4b2019-08-28 19:35:56 -070033 Token InvalidToken() { return events_list_.end(); }
34
35 // Deschedule an event by its iterator
36 void Deschedule(Token token);
37
38 // Runs until exited.
39 void Run();
40 // Runs for a duration.
41 void RunFor(monotonic_clock::duration duration);
42
43 void Exit() { is_running_ = false; }
44
45 bool is_running() const { return is_running_; }
46
47 monotonic_clock::time_point monotonic_now() const { return now_; }
Austin Schuh92547522019-12-28 14:33:43 -080048
Alex Perrycb7da4b2019-08-28 19:35:56 -070049 realtime_clock::time_point realtime_now() const {
Austin Schuh92547522019-12-28 14:33:43 -080050 return realtime_clock::time_point(monotonic_now().time_since_epoch() +
51 realtime_offset_);
52 }
53
54 // Sets realtime clock to realtime_now for a given monotonic clock.
55 void SetRealtimeOffset(monotonic_clock::time_point monotonic_now,
56 realtime_clock::time_point realtime_now) {
57 realtime_offset_ =
58 realtime_now.time_since_epoch() - monotonic_now.time_since_epoch();
Alex Perrycb7da4b2019-08-28 19:35:56 -070059 }
60
61 private:
62 // Current execution time.
63 monotonic_clock::time_point now_ = monotonic_clock::epoch();
Austin Schuh92547522019-12-28 14:33:43 -080064 std::chrono::nanoseconds realtime_offset_ = std::chrono::seconds(0);
Alex Perrycb7da4b2019-08-28 19:35:56 -070065
Austin Schuh39788ff2019-12-01 18:22:57 -080066 std::vector<std::function<void()>> on_run_;
67
Alex Perrycb7da4b2019-08-28 19:35:56 -070068 // Multimap holding times to run functions. These are stored in order, and
69 // the order is the callback tree.
70 ChannelType events_list_;
71 bool is_running_ = false;
72};
73
74} // namespace aos
75
76#endif // AOS_EVENTS_EVENT_SCHEDULER_H_