Skip to main content

Work Queue

Workers perform background tasks based on input and triggers — a cron job that runs on an interval, sending an email after an operation, syncing with an external system, and so on.

Creating a worker​

The recommended way is the registerWorker factory. You pass the work type and a process callback; the factory builds and registers the worker plugin.

import { registerWorker } from '@unchainedshop/core';

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

registerWorker<{ wait?: number; fails?: boolean }, { wait?: number }>({
type: 'DEMO_HEARTBEAT',
process: async (input) => {
if (input?.wait) await wait(input.wait);
if (input?.fails) throw new Error('heartbeat failed'); // a thrown error => { success: false }
return input; // the resolved value => { success: true, result: input }
},
});
OptionDescription
typeWork type — passed to modules.worker.addWork({ type }) to enqueue this work. Keyed shop.unchained.worker.<type lower-cased>.
process(input, workId)The work logic. Return a result (→ { success: true, result }); a thrown error becomes { success: false }.
externaltrue if the work is processed outside the engine (default false).
maxParallelAllocationsConcurrency cap for this work type.

For full control (a custom key/version, or the raw doWork(input, api, workId) shape), build an IWorkerAdapter and register it via pluginRegistry.register() — see Plugin System.

Scheduling recurring work​

schedule takes a ScheduleData structure — build it with the schedule helper exported from @unchainedshop/core (schedule.parse.cron(...) or schedule.parse.text('every 30 minutes')):

import { WorkerDirector, schedule } from '@unchainedshop/core';

WorkerDirector.configureAutoscheduling({
type: 'DEMO_HEARTBEAT',
schedule: schedule.parse.cron('0 * * * *'), // every hour
input: async () => ({ wait: 1000 }),
});

Adding work to the queue​

Enqueue work via the worker module on the Unchained context:

await unchainedAPI.modules.worker.addWork({
type: 'DEMO_HEARTBEAT',
retries: 0,
input: { wait: 1000 },
});