ArPiRobot-CoreLib C++
C++ library for ArPiRobot robots
scheduler.hpp
1 /*
2  * Copyright 2021 Marcus Behel
3  *
4  * This file is part of ArPiRobot-CoreLib.
5  *
6  * ArPiRobot-CoreLib is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Lesser General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * ArPiRobot-CoreLib is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public License
17  * along with ArPiRobot-CoreLib. If not, see <https://www.gnu.org/licenses/>.
18  */
19 
20 #pragma once
21 
22 #include <functional>
23 #include <chrono>
24 #include <memory>
25 #include <atomic>
26 #include <mutex>
27 #include <future>
28 #include <map>
29 #include <ctpl_stl.h>
30 
35 namespace arpirobot{
36 
37  using sched_clk = std::chrono::system_clock;
38 
44  class Task{
45  public:
46  Task(const std::function<void()> &&f);
47 
48  virtual sched_clk::time_point nextRunTime();
49 
50  virtual bool doesRepeat();
51 
52  std::function<void()> targetFunction;
53  };
54 
58  class RepeatedTask : public Task{
59  public:
60  RepeatedTask(const std::function<void()> &&f, sched_clk::duration rate);
61 
62  sched_clk::time_point nextRunTime();
63 
64  bool doesRepeat();
65 
66  sched_clk::duration rate;
67  };
68 
72  class SchedSleeper{
73  public:
74  SchedSleeper();
75 
76  void sleep_for(sched_clk::duration duration);
77 
78  void sleep_until(sched_clk::time_point time);
79 
80  void sleep();
81 
82  void interrupt();
83 
84  private:
85  bool interrupted;
86  std::mutex m;
87  std::condition_variable cv;
88  };
89 
93  class Scheduler{
94  public:
95  Scheduler(unsigned int maxThreads = 4);
96  ~Scheduler();
97 
98  // Add a task to be run once
99  std::shared_ptr<Task> addTask(const std::function<void()> &&targetFunc, sched_clk::time_point::duration delay);
100 
101  // Add a task to be run periodically (at given rate)
102  std::shared_ptr<Task> addRepeatedTask(const std::function<void()> &&targetFunc, sched_clk::time_point::duration delay,
103  sched_clk::time_point::duration rate);
104 
105  // Remove a task (only really useful for repeated tasks)
106  void removeTask(std::shared_ptr<Task> task);
107 
108  private:
109  void serviceTasks();
110 
111  std::atomic<bool> done;
112  SchedSleeper sleeper;
113  std::multimap<sched_clk::time_point, std::shared_ptr<Task>> tasks;
114  std::mutex lock;
115  ctpl::thread_pool threads;
116  };
117 
118 }
Definition: scheduler.hpp:58
Definition: scheduler.hpp:72
Definition: scheduler.hpp:93
Definition: scheduler.hpp:44
Definition: ArduinoDevice.hpp:27