import * as ServiceSpec from "../spec/service" import * as async from "async" export class GracefulShutdownService extends ServiceSpec.GracefulShutdownService { initialize() { process.on("exit", this.exitHandler) process.on("SIGINT", this.exitHandler) process.on("SIGTERM", this.exitHandler) } exitHandlers: { name: string timeout: number handler: Function }[] = [] graceful(option: { name: string timeout?: number }, callback: (done: Function) => void) { this.exitHandlers.push({ name: option.name, timeout: option.timeout || this.settings.gracefulShutdown.timeout, handler: callback }) } onExit() { async.forEachSeries(this.exitHandlers, (todo, done) => { let timer = setTimeout(() => { console.error(`Graceful shutdown timeout for "${todo.name}"`) console.error(`Skip it`) done() done = () => { } }, todo.timeout) todo.handler(() => { done() clearTimeout(timer) done = () => { } }) }, () => { process.exit(0) }) } exitHandler = this.onExit.bind(this) }