blob: 2fcf90b813fe6a12e4fc5da1a9c3ca40b5c9d3e8 [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_; }
48 realtime_clock::time_point realtime_now() const {
49 // TODO(austin): Make this all configurable...
50 return realtime_clock::epoch() + now_.time_since_epoch() +
51 std::chrono::seconds(1000000);
52 }
53
54 private:
55 // Current execution time.
56 monotonic_clock::time_point now_ = monotonic_clock::epoch();
57
Austin Schuh39788ff2019-12-01 18:22:57 -080058 std::vector<std::function<void()>> on_run_;
59
Alex Perrycb7da4b2019-08-28 19:35:56 -070060 // Multimap holding times to run functions. These are stored in order, and
61 // the order is the callback tree.
62 ChannelType events_list_;
63 bool is_running_ = false;
64};
65
66} // namespace aos
67
68#endif // AOS_EVENTS_EVENT_SCHEDULER_H_