forked from robb-j/ProgrammableThings
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgramScheduler.cpp
More file actions
86 lines (76 loc) · 1.78 KB
/
Copy pathProgramScheduler.cpp
File metadata and controls
86 lines (76 loc) · 1.78 KB
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
#include "ProgramScheduler.h"
uint32_t ProgramScheduler::add(JSValue fn, uint32_t nextTick, int32_t interval, JSValue thisValue)
{
Debug::log("ProgramScheduler#add");
auto id = ++idCounter;
JS_DupValue(ctx, fn);
JS_DupValue(ctx, thisValue);
timers.push_back(TimerEntry{id, nextTick, interval, fn, thisValue});
return id;
}
void ProgramScheduler::clear(uint32_t id)
{
Debug::log("ProgramScheduler#clear");
auto item = timers.begin();
while (item != timers.end())
{
if (item->id == id)
{
JS_FreeValue(ctx, item->fn);
JS_FreeValue(ctx, item->thisValue);
item = timers.erase(item);
}
else
{
item++;
}
}
}
void ProgramScheduler::clearAll()
{
Debug::log("ProgramScheduler#clearAll");
auto item = timers.begin();
while (item != timers.end())
{
JS_FreeValue(ctx, item->fn);
JS_FreeValue(ctx, item->thisValue);
item = timers.erase(item);
}
}
void ProgramScheduler::tick(uint32_t now)
{
// Debug::log("ProgramScheduler#tick");
auto item = timers.begin();
while (item != timers.end())
{
if (item->nextTick > now)
{
// Debug::log("- skip: " + item->id);
item++;
continue;
}
Debug::log("- running: " + item->id);
auto result = JS_Call(ctx, item->fn, item->thisValue, 0, nullptr);
if (JS_IsException(result) && exceptionHandler != nullptr)
{
exceptionHandler(ctx, result);
}
if (item->interval == -1 || item->interval == 0)
{
Debug::log("- disposing");
JS_FreeValue(ctx, item->fn);
JS_FreeValue(ctx, item->thisValue);
item = timers.erase(item);
}
else
{
// Debug::log("- rescheduling");
item->nextTick += item->interval;
item++;
}
}
}
bool ProgramScheduler::isInactive()
{
return timers.empty();
}