Skip to content

Instantly share code, notes, and snippets.

@VitorLuizC
Last active March 8, 2017 15:22
Show Gist options
  • Select an option

  • Save VitorLuizC/ad6bd45c2f5456ae0116203e6bc8157f to your computer and use it in GitHub Desktop.

Select an option

Save VitorLuizC/ad6bd45c2f5456ae0116203e6bc8157f to your computer and use it in GitHub Desktop.
Node.js simple service. Run a callback in an interval.
class Service {
/**
* Creates a new service.
* @param {function} service
* @param {number} time Time interval in minutes.
*/
constructor(service, time) {
const MINUTE = 1000 * 60;
this.time = MINUTE * time;
this.times = 0;
this.interval = null;
this.service = () => {
service();
this.times++;
};
}
start() {
/** Run immediately. */
this.service();
/**
* Starts time interval.
*/
this.id = setInterval(this.service, this.time);
}
stop() {
if (this.id === null)
throw new Error('Service is already stopped.');
clearInterval(this.id);
this.id = null;
}
}
module.exports = (service, time) => new Service(service, time);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment