正常停止函数的定期执行



在typecipt/nodejs中,我怎样才能优雅地关闭一个重复做事的组件。 即,我希望用户能够发送SIGINT信号,例如通过按 <ctrl+c> 来优雅地停止程序:

export class Repeater {
private running: boolean;
constructor() {
this.running = false;
}
public do(): void {
this.running = true;
setTimeout(() => {
if (this.running) {
// do stuff
this.do();
}
}, 3000);
}
public stop(): void {
this.running = false;
}
}

用法:

const repeater = new Repeater();
process.on("SIGINT", () => {
repeater.stop();
process.exit();
});
repeater.start();

我从上面的代码开始,但是缺少的是调用stop()实际上阻塞的部分,直到当前执行完成do()

您可以从stop方法返回一个承诺,并在解析后退出进程。将其设置为在间隔结束后不再truerunning时解决:

您引用了一个未显示的start方法,因此我在下面的代码中创建了一个方法。

TS游乐场

export class Repeater {
private running: boolean = false;
private finalize: () => void = () => {};
private done: Promise<void> = new Promise(resolve => this.finalize = resolve);
public do(): void {
// do stuff
setTimeout(() => {
if (this.running) this.do();
else this.finalize();
}, 3000);
}
public start(): void {
if (!this.running) {
this.running = true;
this.done = new Promise(resolve => this.finalize = resolve);
this.do();
}
}
public stop(): Promise<void> {
this.running = false;
return this.done;
}
}
const repeater = new Repeater();
process.on("SIGINT", () => {
repeater.stop().then(() => process.exit());
});
repeater.start();

最新更新