habitica/migrations/utils/timer.js

44 lines
982 B
JavaScript
Raw Normal View History

2019-10-08 14:57:10 +00:00
const logger = require('./logger');
2016-06-03 11:36:20 +00:00
class Timer {
2019-10-08 16:36:55 +00:00
constructor (options = {}) {
2019-10-08 14:57:10 +00:00
const warningThreshold = options.minutesWarningThreshold || 10;
2016-06-03 11:36:20 +00:00
this.count = 0;
this._minutesWarningThreshold = warningThreshold * 60;
if (!options.disableAutoStart) this.start();
}
2019-10-08 14:57:10 +00:00
2016-06-03 11:36:20 +00:00
start () {
this._internalTimer = setInterval(() => {
2019-10-08 16:36:55 +00:00
this.count *= 1;
2016-06-03 11:36:20 +00:00
2019-10-08 14:57:10 +00:00
const shouldWarn = this._minutesWarningThreshold < this.count;
const logStyle = shouldWarn ? 'error' : 'warn';
const dangerMessage = shouldWarn ? 'DANGER: ' : '';
2016-06-03 11:36:20 +00:00
if (this.count % 30 === 0) {
logger[logStyle](`${dangerMessage}Process has been running for`, this.count / 60, 'minutes');
}
}, 1000);
}
2019-10-08 14:57:10 +00:00
2016-06-03 11:36:20 +00:00
stop () {
if (!this._internalTimer) {
throw new Error('Timer has not started');
}
clearInterval(this._internalTimer);
}
get seconds () {
return this.count;
}
get minutes () {
return this.count / 60;
}
}
module.exports = Timer;