|
2 | 2 | title: Creating Jobs |
3 | 3 | description: Learn how to create and add jobs to the queue with various options. |
4 | 4 | --- |
5 | | -}) |
6 | | - |
7 | | -console.log(`Job ${job.id} added to the queue`) |
8 | | -``` |
9 | | -
|
10 | | -## Job Options |
11 | | -
|
12 | | -Jobs support various options to control their behavior: |
13 | | -
|
14 | | -```typescript |
15 | | -await queue.add( |
16 | | - { task: 'process-pdf', url: 'https://example.com/document.pdf' }, |
17 | | - { |
18 | | - delay: 5000, // Delay for 5 seconds before processing |
19 | | - attempts: 3, // Retry up to 3 times on failure |
20 | | - backoff: { |
21 | | - type: 'exponential', // 'fixed' or 'exponential' backoff |
22 | | - delay: 1000, // Base delay in milliseconds |
23 | | - }, |
24 | | - priority: 10, // Higher number = higher priority |
25 | | - removeOnComplete: true, // Remove job when completed |
26 | | - lifo: false, // Process in FIFO order (default) |
27 | | - jobId: 'custom-id', // Provide a custom job ID |
28 | | - timeout: 30000, // Job timeout in milliseconds |
29 | | - } |
30 | | -) |
31 | | -``` |
32 | | - |
33 | | -## Delayed Jobs |
34 | | - |
35 | | -Schedule jobs to run after a specific delay: |
36 | | - |
37 | | -```typescript |
38 | | -// Add a job that will be processed after 30 seconds |
39 | | -await queue.add( |
40 | | - { task: 'send-reminder', userId: 123 }, |
41 | | - { delay: 30000 } |
42 | | -) |
43 | | - |
44 | | -// Schedule a job for a specific time |
45 | | -const futureTime = new Date('2024-12-25T10:00:00').getTime() |
46 | | -const delay = futureTime - Date.now() |
47 | | - |
48 | | -await queue.add( |
49 | | - { task: 'send-christmas-greeting' }, |
50 | | - { delay } |
51 | | -) |
52 | | -``` |
53 | | - |
54 | | -## Job Dependencies |
55 | | - |
56 | | -Jobs can depend on other jobs and will only run after their dependencies complete: |
57 | 5 |
|
58 | 6 | ```typescript |
59 | | -// First job - create report data |
60 | | -const dataJob = await queue.add({ |
61 | | - task: 'generate-report-data', |
62 | | - reportId: 'monthly-sales' |
63 | | -}) |
64 | | - |
65 | | -// Second job - depends on first job |
66 | | -const pdfJob = await queue.add( |
67 | | - { task: 'generate-pdf', reportId: 'monthly-sales' }, |
68 | | - { dependsOn: dataJob.id } |
69 | | -) |
70 | | - |
71 | 7 | // Third job - depends on multiple jobs |
72 | 8 | const emailJob = await queue.add( |
73 | 9 | { task: 'send-report-email', reportId: 'monthly-sales' }, |
|
0 commit comments