Last active
February 19, 2020 19:28
-
-
Save gabrielsaints/afc803eda44407ec6ce8ad37788c0eaa to your computer and use it in GitHub Desktop.
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
type CallbackRunnerType = (startDate?: Date) => void | Promise<void>; | |
export default class Runner { | |
private milliseconds: number; | |
private exit: boolean; | |
constructor(milliseconds: number) { | |
this.milliseconds = milliseconds; | |
this.exit = false; | |
} | |
public async emergency() { | |
this.exit = true; | |
} | |
public async start(callback: CallbackRunnerType): Promise<void> { | |
while (Infinity) { | |
try { | |
const date = new Date(); | |
if (this.exit) { | |
break; | |
} | |
await callback(date); | |
} catch (err) { | |
console.error(err); | |
} finally { | |
if (this.exit) { | |
break; | |
} | |
await this.delay(); | |
} | |
} | |
} | |
private async delay(): Promise<void> { | |
await new Promise(resolve => | |
setTimeout(() => { | |
resolve(); | |
}, this.milliseconds) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment