/
node-cron.js
67 lines (59 loc) · 1.81 KB
/
node-cron.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
'use strict';
const ScheduledTask = require('./scheduled-task');
const BackgroundScheduledTask = require('./background-scheduled-task');
const validation = require('./pattern-validation');
const storage = require('./storage');
module.exports = (() => {
/**
* Creates a new task to execute given function when the cron
* expression ticks.
*
* @param {string} expression - cron expression.
* @param {Function} func - task to be executed.
* @param {Object} options - a set of options for the scheduled task:
* - scheduled <boolean>: if a schaduled task is ready and running to be
* performed when the time mach with the cron excpression.
* - timezone <string>: the tiemzone to execute the tasks.
*
* Example:
* {
* "scheduled": true,
* "timezone": "America/Sao_Paulo"
* }
*
* @returns {ScheduledTask} update function.
*/
function schedule(expression, func, options) {
let task = createTask(expression, func, options);
storage.save(task);
return task;
}
function createTask(expression, func, options){
if(typeof func === 'string'){
return new BackgroundScheduledTask(expression, func, options);
}
return new ScheduledTask(expression, func, options);
}
/**
* Check if a cron expression is valid
* @param {string} expression - cron expression.
*
* @returns {boolean} - returns true if expression is valid
*/
function validate(expression) {
try {
validation(expression);
} catch(e) {
return false;
}
return true;
}
function getTasks() {
return storage.getTasks();
}
return {
schedule: schedule,
validate: validate,
getTasks: getTasks
};
})();