3
0
mirror of https://github.com/reality/dbot.git synced 2024-11-27 14:29:29 +01:00
dbot/modules/timers/timers.js

67 lines
2.3 KiB
JavaScript
Raw Normal View History

/**
* Module Name: Timers
* Description: Persistent timers and shit
*/
var _ = require('underscore')._;
var timers = function(dbot) {
this.timers = dbot.db.timers;
this.runningTimeouts = [];
this.runningIntervals = [];
this.api = {
2013-01-20 22:57:14 +01:00
'addTimer': function(timeout, callback, firstDate) {
var now = new Date().getTime();
if(firstDate) {
console.log('Setting first timer to run at ' + firstDate);
firstTimeout = firstDate.getTime() - now;
2013-01-29 01:53:37 +01:00
this.runningTimeouts.push(setTimeout(function() {
console.log('Running first timer at ' + new Date().toUTCString());
2013-01-20 22:57:14 +01:00
this.runningIntervals.push(this.api.addTimer(timeout, callback));
2013-01-27 16:19:56 +01:00
try {
callback();
} catch(err) {
console.log('Callback failed: ' + err);
}
2013-01-29 01:53:37 +01:00
}.bind(this), firstTimeout));
} else {
2013-01-27 15:49:22 +01:00
this.runningIntervals.push(setInterval(function() {
console.log('Running subsequent timer at ' + new Date().toUTCString());
2013-01-27 16:19:56 +01:00
try {
callback();
} catch(err) {
console.log('Callback failed: ' + err);
}
}.bind(this), timeout));
}
2013-06-09 17:25:06 +02:00
},
'addTimeout': function(date, callback, params) {
2013-06-09 17:25:31 +02:00
var now = new Date().getTime(),
2013-06-09 17:25:06 +02:00
timeout = date.getTime() - now;
this.runningTimeouts.push(setTimeout(function() {
try {
callback.apply(callback, params);
} catch(err) {
console.log('Callback failed: ' + err);
}
}, timeout));
}
};
this.onDestroy = function() {
2013-01-27 16:19:56 +01:00
for(var i=0;i<this.runningTimeouts.length;i++) {
2013-01-29 01:53:37 +01:00
console.log('destroying ' +this.runningTimeouts[i]);
clearTimeout(this.runningTimeouts[i]);
}
2013-01-27 16:19:56 +01:00
for(i=0;i<this.runningIntervals.length;i++) {
2013-01-29 01:53:37 +01:00
console.log('destroying ' +this.runningIntervals[i]);
2013-01-27 16:19:56 +01:00
clearInterval(this.runningIntervals[i]);
}
}.bind(this);
};
exports.fetch = function(dbot) {
return new timers(dbot);
};