-
Notifications
You must be signed in to change notification settings - Fork 0
/
scheduler.h
50 lines (42 loc) · 1.01 KB
/
scheduler.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Class for the Task scheduler
//
class Task {
public:
typedef void (*taskCallback)(void);
// Default constructor
Task() : callback(nullptr), interval(0), lastRun(0) {}
Task(taskCallback cb, unsigned long intervalMillis) : callback(cb), interval(intervalMillis) {
lastRun = millis();
}
void runIfDue() {
unsigned long now = millis();
if (now - lastRun >= interval) {
lastRun = now;
callback();
}
}
private:
taskCallback callback;
unsigned long interval;
unsigned long lastRun;
};
class TaskScheduler {
public:
TaskScheduler() {
taskCount = 0; // Initialize taskCount
}
void addTask(Task::taskCallback cb, unsigned long intervalMillis) {
if (taskCount < MAX_TASKS) {
tasks[taskCount++] = Task(cb, intervalMillis);
}
}
void runTasks() {
for (int i = 0; i < taskCount; ++i) {
tasks[i].runIfDue();
}
}
private:
static const int MAX_TASKS = 10; // Max number of tasks that can be scheduled.
Task tasks[MAX_TASKS];
int taskCount;
};