Skip to content

Instantly share code, notes, and snippets.

@gabrielsaints
Last active February 19, 2020 19:28
Show Gist options
  • Save gabrielsaints/afc803eda44407ec6ce8ad37788c0eaa to your computer and use it in GitHub Desktop.
Save gabrielsaints/afc803eda44407ec6ce8ad37788c0eaa to your computer and use it in GitHub Desktop.
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