-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscheduled-task.js
executable file
·92 lines (78 loc) · 1.79 KB
/
scheduled-task.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
'use strict'
/**
* Creates a new scheduled task.
*
* @param {Task} task - task to schedule.
* @param {*} options - task options.
*/
function ScheduledTask (task, options) {
// var timezone = options.timezone;
/**
* Starts updating the task.
*
* @return {ScheduledTask} instance of this task.
*/
this.start = () => {
this.status = 'scheduled'
if (this.task && !this.tick) {
var date = new Date()
this.tick = setTimeout(this.task.bind(this), 500 - date.getMilliseconds())
}
return this
}
/**
* Stops updating the task.
*
* @return {ScheduledTask} instance of this task.
*/
this.stop = () => {
this.status = 'stoped'
if (this.tick) {
clearTimeout(this.tick)
this.tick = null
}
return this
}
/**
* Returns the current task status.
*
* @return {string} current task status.
* The return may be:
* - scheduled: when a task is scheduled and waiting to be executed.
* - running: the task status while the task is executing.
* - stoped: when the task is stoped.
* - destroyed: whe the task is destroyed, in that status the task cannot be re-started.
* - failed: a task is maker as failed when the previous execution fails.
*/
this.getStatus = () => {
return this.status
}
/**
* Destroys the scheduled task.
*/
this.destroy = () => {
this.stop()
this.status = 'destroyed'
this.task = null
}
task.on('started', () => {
this.status = 'running'
})
task.on('done', () => {
this.status = 'scheduled'
})
task.on('failed', () => {
this.status = 'failed'
})
this.task = () => {
var date = new Date()
this.tick = setTimeout(this.task.bind(this),
500)
task.update(date)
}
this.tick = null
if (options.scheduled !== false) {
this.start()
}
}
module.exports = ScheduledTask