0
0
NestJSframework~5 mins

Job options (delay, attempts, priority) in NestJS

Choose your learning style9 modes available
Introduction

Job options help control how and when background tasks run. They let you delay jobs, retry failed jobs, and set job importance.

You want to run a task after some waiting time, like sending a reminder email later.
You want to retry a task if it fails, like trying to save data again after a network error.
You want important jobs to run before less important ones, like processing urgent orders first.
Syntax
NestJS
queue.add('jobName', data, { delay: number, attempts: number, priority: number })

delay is in milliseconds and delays job start.

attempts sets the maximum number of attempts for the job (including the first one).

priority is a number where lower means higher priority.

Examples
This delays the email job by 60 seconds before running.
NestJS
queue.add('sendEmail', { to: 'user@example.com' }, { delay: 60000 })
This retries the order processing up to 3 times if it fails.
NestJS
queue.add('processOrder', { orderId: 123 }, { attempts: 3 })
This sets the report job to high priority (1 is high).
NestJS
queue.add('generateReport', {}, { priority: 1 })
Sample Program

This example shows a job that sends a welcome email. It waits 5 seconds before starting, tries up to 2 times, and has medium priority (5).

If the job ultimately fails after all attempts, the @OnQueueFailed handler logs the failure.

NestJS
import { Processor, Process, OnQueueFailed } from '@nestjs/bull';
import { Job } from 'bull';

@Processor('email')
export class EmailProcessor {
  @Process('sendWelcome')
  async handleSendWelcome(job: Job) {
    console.log(`Sending welcome email to ${job.data.email}`);
    if (Math.random() < 0.5) {
      throw new Error('Random failure');
    }
    return 'Email sent';
  }

  @OnQueueFailed()
  onFailed(job: Job, error: Error) {
    console.log(`Job ${job.id} failed: ${error.message}`);
  }
}

// Adding a job with options
queue.add('sendWelcome', { email: 'user@example.com' }, { delay: 5000, attempts: 2, priority: 5 });
OutputSuccess
Important Notes

Delay uses milliseconds, so 1000 means 1 second.

Attempts help handle temporary errors by retrying jobs automatically.

Priority lets you control job order: lower numbers run first.

Summary

Job options control timing, retries, and order of background tasks.

Use delay to wait before running a job.

Use attempts to retry failed jobs automatically.

Use priority to run important jobs first.