Skip to content

Examples

Use these examples as starting points for the current Job task, enqueue, delay, retry, status, cancel, and replay APIs.

Terminal window
const jobs = job({
name: "background",
})
app.use(jobs)
jobs.task("sync-account", {
retry: {
attempts: 3,
},
}, async (payload) => {
await provider.syncAccount(payload.accountId)
})
await jobs.enqueue("sync-account", {
accountId: "acct_123",
})
Terminal window
jobs.task("send-trial-ending-notice", {}, async (payload) => {
await notifications.sendTrialEndingNotice(payload.userId)
})
await jobs.enqueue("send-trial-ending-notice", {
userId: "user_123",
}, {
runAt: "2026-06-01T09:00:00.000Z",
})
Terminal window
const jobs = job({
name: "webhook-jobs",
namespace: "webhooks",
})
jobs.task("deliver-webhook", {
retry: {
attempts: 8,
backoff: {
type: "custom",
delaysSeconds: [10, 30, 120, 300, 900, 3600, 21600],
},
},
}, async (payload, ctx) => {
const response = await fetch(payload.url, {
method: "POST",
headers: {
"content-type": "application/json",
"x-layeron-event-id": payload.eventId,
},
body: JSON.stringify(payload.body),
})
if (!response.ok) {
throw new Error(`webhook delivery failed: ${response.status}`)
}
})
await jobs.enqueue("deliver-webhook", {
endpointId: "ep_123",
eventId: "evt_123",
url: "https://example.com/webhook",
body: {
type: "invoice.paid",
},
}, {
idempotencyKey: "webhook:ep_123:evt_123",
})
Terminal window
jobs.task("send-welcome-notice", {
retry: {
attempts: 5,
backoff: "exponential",
},
}, async (payload) => {
await notifications.send({
userId: payload.userId,
template: "welcome",
})
})
app.post("/signup", async (request) => {
const body = await request.json()
await jobs.enqueue("send-welcome-notice", {
userId: body.userId,
}, {
idempotencyKey: `welcome:${body.userId}`,
})
return Response.json({ ok: true })
})
Terminal window
jobs.task("process-upload", {
retry: {
attempts: 3,
},
}, async (payload) => {
const object = await files.get(payload.objectKey)
await createThumbnail(object)
await extractMetadata(object)
})
await jobs.enqueue("process-upload", {
objectKey: "uploads/avatar.png",
})
Terminal window
await jobs.enqueue("rebuild-search-index", {
tenantId: "tenant_123",
}, {
delaySeconds: 300,
})
Terminal window
const run = await jobs.enqueue("send-trial-ending-notice", {
userId: "user_123",
}, {
delaySeconds: 86400,
})
await jobs.runs.cancel(run.runId)
Terminal window
const failed = await jobs.runs.list({
taskName: "deliver-webhook",
status: "dead_lettered",
limit: 50,
})
for (const run of failed.runs) {
await jobs.runs.replay(run.runId, {
reason: "provider recovered",
})
}