3
0
mirror of https://github.com/reality/dbot.git synced 2024-12-24 19:52:36 +01:00

This should be a fully functional timers module [#160]

This commit is contained in:
reality 2013-01-20 21:27:49 +00:00
parent 07656eddcd
commit d9bd2eb492

View File

@ -6,30 +6,36 @@ var _ = require('underscore')._;
var timers = function(dbot) { var timers = function(dbot) {
this.timers = dbot.db.timers; this.timers = dbot.db.timers;
this.runningTimers = []; this.runningTimeouts = [];
this.runningIntervals = [];
this.api = { this.api = {
'addTimer': function(callback, timeout, firstDate) { 'addTimer': function(callback, timeout, firstDate) {
var now = new Date().getTime(); var now = new Date().getTime();
if(firstDate) { if(firstDate) {
console.log('Setting first timer to run at ' + firstDate); console.log('Setting first timer to run at ' + firstDate);
timeout = firstDate.getTime() - now; firstTimeout = firstDate.getTime() - now;
setTimeout(function(callback) { setTimeout(function(callback) {
console.log('Running first timer at ' + new Date().toUTCString()); console.log('Running first timer at ' + new Date().toUTCString());
this.runningIntervals.push(this.api.addTimer(callback, timeout));
callback(); callback();
this.api.addTimer(callback, timeout); }.bind(this), firstTimeout);
}.bind(this), timeout);
} else { } else {
setInterval(function(callback) { this.runningIntervals.push(setInterval(function(callback) {
console.log('Running subsequent timer at ' + new Date().toUTCString()); console.log('Running subsequent timer at ' + new Date().toUTCString());
callback(); callback();
}.bind(this), timeout); }.bind(this), timeout));
} }
} }
}; };
this.onLoad = function() { this.onDestroy = function() {
// TODO: Persist timers for(var i=0;i<this.runningTimeouts;i++ {
clearTimeout(this.runningTimeouts[i]);
}
for(i=0;i<this.runningIntervals;i++ {
clearTimer(this.runningIntervals[i]);
}
}.bind(this); }.bind(this);
}; };