stop running new tasks after shutdown

Signed-off-by: bnechyporenko <bnechyporenko@bol.com>
This commit is contained in:
bnechyporenko
2024-01-21 12:37:35 +01:00
parent 03cb5dc5d0
commit 04bab8a81a
2 changed files with 17 additions and 5 deletions
@@ -76,8 +76,10 @@ export type CreateWorkerOptions = {
export class TaskWorker {
private taskQueue: PQueue;
private logger: Logger | undefined;
private stopWorkers: boolean;
private constructor(private readonly options: TaskWorkerOptions) {
this.stopWorkers = false;
this.logger = options.logger;
this.taskQueue = new PQueue({
concurrency: options.concurrentTasksLimit,
@@ -120,26 +122,31 @@ export class TaskWorker {
await this.options.taskBroker.recoverTasks?.();
} catch (err) {
this.logger?.error(stringifyError(err));
// ignore
}
}
start() {
(async () => {
for (;;) {
while (!this.stopWorkers) {
await new Promise(resolve => setTimeout(resolve, 10000));
await this.recoverTasks();
}
})();
(async () => {
for (;;) {
while (!this.stopWorkers) {
await this.onReadyToClaimTask();
const task = await this.options.taskBroker.claim();
this.taskQueue.add(() => this.runOneTask(task));
if (!this.stopWorkers) {
const task = await this.options.taskBroker.claim();
void this.taskQueue.add(() => this.runOneTask(task));
}
}
})();
}
stop() {
this.stopWorkers = true;
}
protected onReadyToClaimTask(): Promise<void> {
if (this.taskQueue.pending < this.options.concurrentTasksLimit) {
return Promise.resolve();
@@ -336,8 +336,13 @@ export async function createRouter(
const launchWorkers = () => workers.forEach(worker => worker.start());
const shutdownWorkers = () => {
workers.forEach(worker => worker.stop());
};
if (options.lifecycle) {
options.lifecycle.addStartupHook(launchWorkers);
options.lifecycle.addShutdownHook(shutdownWorkers);
} else {
launchWorkers();
}