UNPKG

@penkov/tasks_queue

Version:

A lightweight PostgreSQL-backed task queue system with scheduling, retries, backoff strategies, and priority handling. Designed for efficiency and observability in modern Node.js applications.

53 lines (52 loc) 1.83 kB
import log4js from "log4js"; import { TasksQueueWorker } from "./tasks-queue.worker.js"; import { TasksAuxiliaryWorker } from "./tasks-auxiliary-worker.js"; import { none, some } from "scats"; import { TaskPeriodType, } from "./tasks-model.js"; const logger = log4js.getLogger("TasksQueueService"); export class TasksQueueService { tasksQueueDao; worker; auxiliaryWorker; constructor(tasksQueueDao, manageTasksQueueService, config) { this.tasksQueueDao = tasksQueueDao; this.worker = new TasksQueueWorker(this.tasksQueueDao, config.concurrency, config.loopInterval); if (config.runAuxiliaryWorker) { this.auxiliaryWorker = some(new TasksAuxiliaryWorker(tasksQueueDao, manageTasksQueueService)); } else { this.auxiliaryWorker = none; } } async schedule(task) { await this.tasksQueueDao.schedule(task); this.taskScheduled(task.queue); } async scheduleAtFixedRate(task) { await this.tasksQueueDao.schedulePeriodic(task, TaskPeriodType.fixed_rate); this.taskScheduled(task.queue); } async scheduleAtFixedDelay(task) { await this.tasksQueueDao.schedulePeriodic(task, TaskPeriodType.fixed_delay); this.taskScheduled(task.queue); } taskScheduled(queueName) { this.worker.tasksScheduled(queueName); } registerWorker(queueName, worker) { this.worker.registerWorker(queueName, worker); } start() { try { this.worker.start(); this.auxiliaryWorker.foreach((w) => w.start()); } catch (e) { logger.warn("Failed to process stalled tasks", e); } } async stop() { await this.auxiliaryWorker.mapPromise((w) => w.stop()); await this.worker.stop(); } }