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.
Example: Full Setup
Section titled “Example: Full Setup”1. Define a Job
Section titled “1. Define a Job”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 settingsconst client = new DomusJobClient({ host: 'localhost', port: 6379, password: 'your_password',});
// Create a queueconst queue = client.createQueue('basic_queue');
// Add a worker for the queueconst worker = client.createWorker(queue, [HelloWorldJob]);
// Enqueue a jobawait queue.add(new HelloWorldJob({ name: 'DomusJS' }));
// Handle worker eventsworker.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.
💡 Core Interfaces Recap
Section titled “💡 Core Interfaces Recap”| Interface | Purpose |
|---|---|
JobTask | Base class representing a task with an execute() method. |
Queue | Provides .add() to enqueue jobs of type JobTask. |
Worker | Processes jobs and emits events (onCompleted, onFailed). |
Job | Represents job metadata (id, name, data, attempts, result, etc.). |
✅ Best Practices
Section titled “✅ Best Practices”- Define one job class per task type for clear separation.
- Always attach
onFailedandonCompletedlisteners 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).