Skip to content

Using the Jobs Module

This guide shows you how to set up and use the DomusJS Jobs Module to handle background tasks using the real interfaces you provide.

✅ We cover:

  • How to define jobs with JobTask.
  • How to set up a queue and enqueue jobs.
  • How to create a worker and handle job events.

hello-world.job.ts
import { JobTask } from '@domusjs/jobs';
type HelloWorldJobData = {
name: string;
};
export class HelloWorldJob extends JobTask {
static readonly jobName = 'hello_world';
constructor(public readonly data: HelloWorldJobData) {
super(data);
}
async execute(): Promise<string> {
const ret = `[HelloWorldJob] Hello ${this.data.name}!`;
return ret;
}
}

✅ This defines a reusable job by extending JobTask, with a clear jobName identifier and its own execute() logic.


2. Set Up Client, Queue, Worker, and Events

Section titled “2. Set Up Client, Queue, Worker, and Events”
import 'reflect-metadata';
import { DomusJobClient } from '@domusjs/jobs';
import { HelloWorldJob } from './hello-world.job';
// Create a client with Redis connection settings
const client = new DomusJobClient({
host: 'localhost',
port: 6379,
password: 'your_password',
});
// Create a queue
const queue = client.createQueue('basic_queue');
// Add a worker for the queue
const worker = client.createWorker(queue, [HelloWorldJob]);
// Enqueue a job
await queue.add(new HelloWorldJob({ name: 'DomusJS' }));
// Handle worker events
worker.onFailed((job, error) => {
console.error('Job failed:', {
jobId: job?.id,
error: error.message,
});
});
worker.onCompleted((job, result) => {
console.info('Job completed:', {
jobId: job?.id,
result,
});
});

✅ This setup ensures:

  • Clean separation between queue, worker, and job definition.
  • Centralized connection management via DomusJobClient.
  • Strong typing and event handling through provided interfaces.

InterfacePurpose
JobTaskBase class representing a task with an execute() method.
QueueProvides .add() to enqueue jobs of type JobTask.
WorkerProcesses jobs and emits events (onCompleted, onFailed).
JobRepresents job metadata (id, name, data, attempts, result, etc.).

  • Define one job class per task type for clear separation.
  • Always attach onFailed and onCompleted listeners for monitoring.
  • Use multiple queues to separate concerns (e.g., EmailQueue, VideoQueue).
  • Keep job payloads minimal and avoid sending large blobs of data.
  • Use Redis connection configurations carefully for production (secured passwords, proper scaling).