Orchestrate your background jobs. Execute jobs in sequence with Chains, or in parallel as a Batch with completion callbacks.
Job chaining allows you to specify a list of queued jobs that should be run in sequence locally or distributed. If one job in the sequence fails, the rest of the jobs will not be run.
1import { Bus } from 'canxjs';2import { OptimizeImage } from './jobs/OptimizeImage';3import { SendNotification } from './jobs/SendNotification';45// Run jobs in sequence. If one fails, the rest are not run.6await Bus.chain([7new OptimizeImage(imageId),8new SendNotification(userId),9]).dispatch();
Job batching allows you to execute a batch of jobs and then perform some action when the batch has completed executing.
1import { Bus } from 'canxjs';23// Run jobs in parallel and track completion4const batch = await Bus.batch([5new ProcessImport(file1),6new ProcessImport(file2),7new ProcessImport(file3),8])9.then(() => {10// Callback when all jobs complete successfully11console.log('Batch finished!');12})13.catch(() => {14// Callback if a job fails15console.log('Batch failed!');16})17.finally(() => {18// Always run19})20.dispatch();2122console.log(`Batch ID: ${batch.id}`);
Your job classes should use the Batchable trait (mixin) to interact with the batch they belong to.
1import { Batchable, Dispatchable, InteractsWithBatch } from 'canxjs';23export class ProcessImport implements Dispatchable, Batchable {4use(InteractsWithBatch);56async handle() {7if (this.batch().cancelled()) {8return;9}1011// Process...12}13}