|
1 | 1 | import { JobDispatcher } from './job_dispatcher.js' |
| 2 | +import { JobBatchDispatcher } from './job_batch_dispatcher.js' |
2 | 3 | import { ScheduleBuilder } from './schedule_builder.js' |
3 | 4 | import type { JobContext, JobOptions } from './types/main.js' |
4 | 5 |
|
@@ -193,6 +194,57 @@ export abstract class Job<Payload = any> { |
193 | 194 | return dispatcher |
194 | 195 | } |
195 | 196 |
|
| 197 | + /** |
| 198 | + * Dispatch multiple jobs to the queue in a single batch. |
| 199 | + * |
| 200 | + * Returns a JobBatchDispatcher for fluent configuration before dispatching. |
| 201 | + * The jobs are not actually dispatched until `.run()` is called or the |
| 202 | + * dispatcher is awaited. |
| 203 | + * |
| 204 | + * This is more efficient than calling `dispatch()` multiple times as it |
| 205 | + * uses batched operations (e.g., Redis pipeline, SQL batch insert). |
| 206 | + * |
| 207 | + * @param payloads - Array of data to pass to each job |
| 208 | + * @returns A JobBatchDispatcher for fluent configuration |
| 209 | + * |
| 210 | + * @example |
| 211 | + * ```typescript |
| 212 | + * // Batch dispatch for newsletter |
| 213 | + * const { jobIds } = await SendEmailJob.dispatchMany([ |
| 214 | + * { to: 'user1@example.com', subject: 'Newsletter' }, |
| 215 | + * { to: 'user2@example.com', subject: 'Newsletter' }, |
| 216 | + * ]) |
| 217 | + * .group('newsletter-jan-2025') |
| 218 | + * .toQueue('emails') |
| 219 | + * .run() |
| 220 | + * |
| 221 | + * console.log(`Dispatched ${jobIds.length} jobs`) |
| 222 | + * ``` |
| 223 | + */ |
| 224 | + static dispatchMany<T extends Job>( |
| 225 | + this: new (...args: any[]) => T, |
| 226 | + payloads: (T extends Job<infer P> ? P : never)[] |
| 227 | + ): JobBatchDispatcher<T extends Job<infer P> ? P : never> { |
| 228 | + const options = (this as any).options || {} |
| 229 | + const jobName = options.name || this.name |
| 230 | + |
| 231 | + const dispatcher = new JobBatchDispatcher<T extends Job<infer P> ? P : never>(jobName, payloads) |
| 232 | + |
| 233 | + if (options.queue) { |
| 234 | + dispatcher.toQueue(options.queue) |
| 235 | + } |
| 236 | + |
| 237 | + if (options.adapter) { |
| 238 | + dispatcher.with(options.adapter) |
| 239 | + } |
| 240 | + |
| 241 | + if (options.priority !== undefined) { |
| 242 | + dispatcher.priority(options.priority) |
| 243 | + } |
| 244 | + |
| 245 | + return dispatcher |
| 246 | + } |
| 247 | + |
196 | 248 | /** |
197 | 249 | * Create a schedule for this job. |
198 | 250 | * |
|
0 commit comments