Skip to content

Instantly share code, notes, and snippets.

@tzechienchu
Created April 25, 2016 09:57
Show Gist options
  • Save tzechienchu/1e39b2ecd95de0ae975cc9b8e8c60126 to your computer and use it in GitHub Desktop.
Save tzechienchu/1e39b2ecd95de0ae975cc9b8e8c60126 to your computer and use it in GitHub Desktop.
var schedule = require('node-schedule');
var ScheduleService = (function () {
var instance;
function init() {
//
// * * * * * *
// ┬ ┬ ┬ ┬ ┬ ┬
// │ │ │ │ │ |
// │ │ │ │ │ └ day of week (0 - 7) (0 or 7 is Sun)
// │ │ │ │ └───── month (1 - 12)
// │ │ │ └────────── day of month (1 - 31)
// │ │ └─────────────── hour (0 - 23)
// │ └──────────────────── minute (0 - 59)
// └───────────────────────── second (0 - 59, OPTIONAL)
//
// Every 1 minute * * * * *
// Every 15 minutes */15 * * * *
// Every 30 minutes */30 * * * *
// Every 1 hour 0 * * * *
// Every 6 hours 0 */6 * * *
// Every 12 hours 0 */12 * * *
// Once a day 4 0 * * *
// Once a week 4 0 * * 0
// Once a month 4 0 1 * *
// Here is a diagram of the general crontab syntax, for illustration:
//
// # +---------------- minute (0 - 59)
// # | +------------- hour (0 - 23)
// # | | +---------- day of month (1 - 31)
// # | | | +------- month (1 - 12)
// # | | | | +---- day of week (0 - 6) (Sunday=0)
// # | | | | |
// * * * * * command to be executed
//
var allScheduleJobs = [];
var getAllJobs = function() {
return allScheduleJobs;
}
var createJobForEveryHour = function(name,cb) {
var job = schedule.scheduleJob('0 * * * *',cb);
allScheduleJobs.push({name:name,date:date,jobId:job});
return job;
}
var createJobForEveryDay = function(cb) {
var job = schedule.scheduleJob('4 0 * * *',cb);
allScheduleJobs.push({name:name,date:date,jobId:job});
return job;
}
var createJob = function(name,date,cb) {
var job = schedule.scheduleJob(date,cb);
allScheduleJobs.push({name:name,date:date,jobId:job});
return job;
}
var cancelJobByName = function(name) {
if (allScheduleJobs.length === 0) return;
allScheduleJobs.forEach(function(job) {
if (job.name === name) {
job.jobId.cancel();
}
})
}
var cancelJob = function(jobId) {
jobId.cancel();
}
//Public Method
return {
createJob:createJob,
cancelJob:cancelJob,
createJobForEveryHour:createJobForEveryHour,
createJobForEveryDay:createJobForEveryDay,
getAllJobs:getAllJobs
};
};
return {
getInstance: function () {
if ( !instance ) {
instance = init();
}
return instance;
}
};
})();
module.exports = ScheduleService;
//
// How to Use the Module
//
// var Util = require('./Utilities');
// var ScheduleService = require('./ScheduleService');
// var mySS = ScheduleService.getInstance();
//
// mySS.createJob('everyMin','* * * * *',function(){
// console.log(Util.getISO8601NowStr());
// })
// console.log(mySS.getAllJobs());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment