Named jobs let you give a clear label to background tasks. This helps you find, manage, or cancel specific jobs easily.
Named jobs in 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.
await emailQueue.add('sendWelcomeEmail', { userId: 123 });
await reportQueue.add('generateReport', { reportId: 456 }, { delay: 60000 });
await notificationQueue.add('sendPush', { deviceId: 'abc' }, { attempts: 3 });
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.
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);
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.
Named jobs let you label background tasks clearly.
This makes managing, tracking, and canceling jobs easier.
Use descriptive names to keep your queues organized.
Practice
named jobs in NestJS queues?Solution
Step 1: Understand the purpose of named jobs
Named jobs provide a clear label to background tasks, making them easier to find and manage.Step 2: Compare options with the purpose
Only They help identify and manage specific background tasks easily. matches this purpose. Options B, C, and D describe unrelated features.Final Answer:
They help identify and manage specific background tasks easily. -> Option BQuick Check:
Named jobs = easier management [OK]
- Thinking named jobs improve speed
- Confusing named jobs with security features
- Assuming named jobs remove the need for queues
Solution
Step 1: Recall the NestJS queue method for adding jobs
The correct method to add a job with a name isqueue.add(name, data).Step 2: Match the method with options
Only queue.add('emailJob', { to: 'user@example.com' }); usesqueue.addwith a job name and data correctly.Final Answer:
queue.add('emailJob', { to: 'user@example.com' }); -> Option DQuick Check:
Use queue.add(name, data) [OK]
- Using non-existent methods like createJob or pushJob
- Forgetting to pass the job name as first argument
- Confusing job execution with job creation
const job = await queue.add('reportGeneration', { userId: 42 });
console.log(job.name);Solution
Step 1: Understand job creation with a name
When adding a job withqueue.add('reportGeneration', data), the job'snameproperty is set to 'reportGeneration'.Step 2: Check the console.log output
Loggingjob.namewill print 'reportGeneration'.Final Answer:
'reportGeneration' -> Option AQuick Check:
Job name property = 'reportGeneration' [OK]
- Assuming default name is used if a name is given
- Expecting undefined if name is not accessed properly
- Thinking job creation throws error without processor
queue.add({ name: 'cleanupJob' }, { force: true });Solution
Step 1: Review the correct syntax for named jobs
Thequeue.addmethod expects the first argument as a string name, not an object.Step 2: Analyze the given code
The code passes an object{ name: 'cleanupJob' }instead of a string, causing a syntax error.Final Answer:
Job name should be a string, not inside an object. -> Option AQuick Check:
First argument to add() = string name [OK]
- Passing job name inside an object instead of string
- Confusing job data with job name argument
- Assuming add() method is missing or invalid
'emailNotification' in a queue. Which approach correctly uses named jobs to achieve this?Solution
Step 1: Understand how to retrieve named jobs
Named jobs can be fetched usingqueue.getJobs(['jobName'])which returns jobs with that name.Step 2: Remove each fetched job
After fetching, callingremove()on each job deletes them from the queue.Final Answer:
Use queue.getJobs(['emailNotification']) and then call remove() on each job. -> Option CQuick Check:
Fetch named jobs then remove [OK]
- Trying to remove jobs by name without fetching them
- Filtering jobs by data instead of name
- Restarting queue does not selectively remove jobs
Ready to prove it?
Pass the test and this pattern moves unknown
