-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
129 lines (110 loc) · 2.76 KB
/
index.js
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
117
118
119
120
121
122
123
124
125
126
127
128
129
let tasks = {};
function RecurringTask(name, functionToExecute, opt = {}) {
let running = false,
updated = Date.now(),
before = opt.before ? opt.before.bind(this) : () => {},
onError = opt.error ? opt.error.bind(this) : () => {},
onSuccess = opt.success ? opt.success.bind(this) : () => {},
after = opt.after ? opt.after.bind(this) : () => {},
timeout =
!isNaN(opt.timeout) && opt.timeout > 0 ? parseInt(opt.timeout) : 60,
delay = !isNaN(opt.delay) && opt.delay > 0 ? parseInt(opt.delay) : 0,
result = null,
goOn = typeof opt.goOn !== 'undefined' ? !!opt.goOn : true,
error = false;
if (tasks[name]) {
throw new Error('There is already a task called ' + name);
}
tasks[name] = this;
this.name = name;
const taskFunction = ~[
'GeneratorFunction',
'AsyncGeneratorFunction'
].indexOf(functionToExecute.constructor.name)
? fromGenerator(functionToExecute).bind(this)
: functionToExecute.bind(this);
this.isRunning = () => running;
this.updated = () => updated;
this.goOn = (...g) => {
if (!g.length) {
return goOn;
}
goOn = !!g[0];
};
this.run = async () => {
error = false;
result = null;
running = true;
await before();
let sleep = new Promise((a, rej) =>
setTimeout(
() => rej(new Error('Task ' + this.name + ' timed out')),
timeout * 1000
)
);
try {
result = await Promise.race([taskFunction(), sleep]);
await onSuccess(result);
} catch (e) {
error = true;
await onError(e);
}
running = false;
updated = Date.now();
await after(result);
await new Promise(acc => setTimeout(() => acc(), delay * 1000));
if (goOn) {
this.run();
}
};
this.status = () => ({
name: this.name,
running,
updated,
goOn,
timeout,
delay,
error
});
}
RecurringTask.stopAllTasks = () => {
for (let t in tasks) {
t = tasks[t];
t.goOn(false);
}
};
RecurringTask.startAllTasks = () => {
for (let t in tasks) {
t = tasks[t];
t.goOn(true);
t.run();
}
};
RecurringTask.statusAll = () => {
let report = [];
for (let t in tasks) {
t = tasks[t];
report.push(t.status());
}
return report;
};
//inspiration: https://dev.to/chromiumdev/cancellable-async-functions-in-javascript-5gp7
function fromGenerator(generator) {
let globalNonce;
return async function(...args) {
const localNonce = (globalNonce = Symbol());
const iter = generator.call(this, ...args);
let result;
for (;;) {
const n = await iter.next();
result = await n.value;
if (n.done) {
return result;
}
if (localNonce !== globalNonce || this.status().error) {
return;
}
}
};
}
module.exports = RecurringTask;