forked from esp8266/Arduino
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ScheduledFunctions.cpp
117 lines (105 loc) · 2.31 KB
/
ScheduledFunctions.cpp
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/*
* ScheduledFunctions.cpp
*
* Created on: 27 apr. 2018
* Author: Herman
*/
#include "ScheduledFunctions.h"
std::list<ScheduledFunctions::ScheduledElement> ScheduledFunctions::scheduledFunctions;
ScheduledFunctions::ScheduledFunctions()
:ScheduledFunctions(UINT_MAX)
{
}
ScheduledFunctions::ScheduledFunctions(unsigned int reqMax)
{
maxElements = reqMax;
}
ScheduledFunctions::~ScheduledFunctions() {
}
ScheduledRegistration ScheduledFunctions::insertElement(ScheduledElement se, bool front)
{
if (countElements >= maxElements)
{
return nullptr;
}
else
{
countElements++;
if (front)
{
scheduledFunctions.push_front(se);
return scheduledFunctions.begin()->registration;
}
else
{
scheduledFunctions.push_back(se);
return scheduledFunctions.rbegin()->registration;
}
}
}
std::list<ScheduledFunctions::ScheduledElement>::iterator ScheduledFunctions::eraseElement(std::list<ScheduledFunctions::ScheduledElement>::iterator it)
{
countElements--;
return scheduledFunctions.erase(it);
}
bool ScheduledFunctions::scheduleFunction(ScheduledFunction sf, bool continuous, bool front)
{
return (insertElement({this,continuous,nullptr,sf}, front) == nullptr);
}
bool ScheduledFunctions::scheduleFunction(ScheduledFunction sf)
{
return scheduleFunction(sf, false, false);
}
ScheduledRegistration ScheduledFunctions::scheduleFunctionReg (ScheduledFunction sf, bool continuous, bool front)
{
return insertElement({this,continuous,std::make_shared<int>(1),sf},front);
}
void ScheduledFunctions::runScheduledFunctions()
{
auto lastElement = scheduledFunctions.end(); // do not execute elements added during runScheduledFunctions
auto it = scheduledFunctions.begin();
while (it != lastElement)
{
bool erase = false;
if (it->registration == nullptr)
{
it->function();
}
else
{
if (it->registration.use_count() > 1)
{
it->function();
}
else
{
erase = true;
}
}
if ((!it->continuous) || (erase))
{
it = it->_this->eraseElement(it);
}
else
{
it++;
}
}
}
void ScheduledFunctions::removeFunction(ScheduledRegistration sr)
{
auto it = scheduledFunctions.begin();
bool removed = false;
while ((!removed) && (it != scheduledFunctions.end()))
{
if (it->registration == sr)
{
it = eraseElement(it);
removed = true;
}
else
{
it++;
}
}
}