2013-01-20 18:55:46 +01:00
|
|
|
/**
|
|
|
|
* Module Name: Timers
|
|
|
|
* Description: Persistent timers and shit
|
|
|
|
*/
|
|
|
|
var _ = require('underscore')._;
|
|
|
|
|
|
|
|
var timers = function(dbot) {
|
|
|
|
this.timers = dbot.db.timers;
|
2013-01-20 22:27:49 +01:00
|
|
|
this.runningTimeouts = [];
|
|
|
|
this.runningIntervals = [];
|
2013-01-20 18:55:46 +01:00
|
|
|
|
|
|
|
this.api = {
|
|
|
|
'addTimer': function(callback, timeout, firstDate) {
|
|
|
|
var now = new Date().getTime();
|
|
|
|
if(firstDate) {
|
|
|
|
console.log('Setting first timer to run at ' + firstDate);
|
2013-01-20 22:27:49 +01:00
|
|
|
firstTimeout = firstDate.getTime() - now;
|
2013-01-20 18:55:46 +01:00
|
|
|
setTimeout(function(callback) {
|
|
|
|
console.log('Running first timer at ' + new Date().toUTCString());
|
2013-01-20 22:27:49 +01:00
|
|
|
this.runningIntervals.push(this.api.addTimer(callback, timeout));
|
2013-01-20 18:55:46 +01:00
|
|
|
callback();
|
2013-01-20 22:27:49 +01:00
|
|
|
}.bind(this), firstTimeout);
|
2013-01-20 18:55:46 +01:00
|
|
|
} else {
|
2013-01-20 22:27:49 +01:00
|
|
|
this.runningIntervals.push(setInterval(function(callback) {
|
2013-01-20 18:55:46 +01:00
|
|
|
console.log('Running subsequent timer at ' + new Date().toUTCString());
|
|
|
|
callback();
|
2013-01-20 22:27:49 +01:00
|
|
|
}.bind(this), timeout));
|
2013-01-20 18:55:46 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2013-01-20 22:27:49 +01:00
|
|
|
this.onDestroy = function() {
|
2013-01-20 22:28:44 +01:00
|
|
|
for(var i=0;i<this.runningTimeouts;i++) {
|
2013-01-20 22:27:49 +01:00
|
|
|
clearTimeout(this.runningTimeouts[i]);
|
|
|
|
}
|
2013-01-20 22:28:44 +01:00
|
|
|
for(i=0;i<this.runningIntervals;i++) {
|
2013-01-20 22:27:49 +01:00
|
|
|
clearTimer(this.runningIntervals[i]);
|
|
|
|
}
|
2013-01-20 18:55:46 +01:00
|
|
|
}.bind(this);
|
|
|
|
};
|
|
|
|
|
|
|
|
exports.fetch = function(dbot) {
|
|
|
|
return new timers(dbot);
|
|
|
|
};
|