Named jobs let you give a clear label to background tasks. This helps you find, manage, or cancel specific jobs easily.
0
0
Named jobs in NestJS
Introduction
You want to run a background task like sending emails and track it by name.
You need to update or remove a specific job later by referring to its name.
You want to organize multiple jobs and avoid confusion by naming each one.
You want to check the status of a particular job in your queue.
You want to prevent duplicate jobs by checking if a named job already exists.
Syntax
NestJS
queue.add('jobName', data, options);The first argument is the job's name as a string.
The second argument is the data the job needs.
Examples
Adds a job named 'sendWelcomeEmail' with user data to the email queue.
NestJS
await emailQueue.add('sendWelcomeEmail', { userId: 123 });
Adds a delayed job named 'generateReport' that starts after 60 seconds.
NestJS
await reportQueue.add('generateReport', { reportId: 456 }, { delay: 60000 });
Adds a job named 'sendPush' with retry attempts set to 3.
NestJS
await notificationQueue.add('sendPush', { deviceId: 'abc' }, { attempts: 3 });
Sample Program
This example shows how to add a named job 'sendWelcomeEmail' to an email queue in NestJS. The processor listens for jobs with that name and runs the handler. The service adds the job with user data.
NestJS
import { Processor, Process } from '@nestjs/bull'; import { Job } from 'bull'; @Processor('email') export class EmailProcessor { @Process('sendWelcomeEmail') async handleSendWelcomeEmail(job: Job) { console.log(`Sending welcome email to user ${job.data.userId}`); // Simulate email sending logic here } } // Somewhere in your service or controller import { InjectQueue } from '@nestjs/bull'; import { Queue } from 'bull'; export class EmailService { constructor(@InjectQueue('email') private emailQueue: Queue) {} async sendWelcome(userId: number) { await this.emailQueue.add('sendWelcomeEmail', { userId }); } } // Usage example // Assume emailQueueInstance is an instance of Queue injected properly const emailService = new EmailService(emailQueueInstance); emailService.sendWelcome(42);
OutputSuccess
Important Notes
Named jobs help you organize and control your background tasks better.
You can have multiple processors for different named jobs in the same queue.
Always use meaningful names to make your code easier to understand.
Summary
Named jobs let you label background tasks clearly.
This makes managing, tracking, and canceling jobs easier.
Use descriptive names to keep your queues organized.