Last active
March 8, 2017 15:22
-
-
Save VitorLuizC/ad6bd45c2f5456ae0116203e6bc8157f to your computer and use it in GitHub Desktop.
Node.js simple service. Run a callback in an interval.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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