blob: 66d34b31db7b3081a715da37c1697f068dd5766f [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
28 Token InvalidToken() { return events_list_.end(); }
29
30 // Deschedule an event by its iterator
31 void Deschedule(Token token);
32
33 // Runs until exited.
34 void Run();
35 // Runs for a duration.
36 void RunFor(monotonic_clock::duration duration);
37
38 void Exit() { is_running_ = false; }
39
40 bool is_running() const { return is_running_; }
41
42 monotonic_clock::time_point monotonic_now() const { return now_; }
43 realtime_clock::time_point realtime_now() const {
44 // TODO(austin): Make this all configurable...
45 return realtime_clock::epoch() + now_.time_since_epoch() +
46 std::chrono::seconds(1000000);
47 }
48
49 private:
50 // Current execution time.
51 monotonic_clock::time_point now_ = monotonic_clock::epoch();
52
53 // Multimap holding times to run functions. These are stored in order, and
54 // the order is the callback tree.
55 ChannelType events_list_;
56 bool is_running_ = false;
57};
58
59} // namespace aos
60
61#endif // AOS_EVENTS_EVENT_SCHEDULER_H_