Triggering from your app
Coming from Trigger.dev
Bok Joy keeps Trigger.dev's names where the behavior matches, in your tasks and in your backend. This page lists every place it differs, and what to change when you move a project over.
On this page
- Triggering from your backend
- Statuses and flags
- Idempotency keys
- Options Bok Joy refuses
- Delays and debounces
- Tags and run lists
- Queues and concurrency limits
- Scheduled tasks
- Realtime in the browser
- Waiting on child runs
- Waiting as a workflow
- Lifecycle hooks
- Not in Bok Joy yet
- Deploying a Trigger.dev project
- Convert a project with the codemod
- Import dashboard schedules
- Defining tasks
Most code moves over with an import change, and a codemod makes it. Task files import from @bokjoy/sdk/trigger instead of @trigger.dev/sdk, and keep their task(), schemaTask() and schedules.task() definitions: see Defining tasks. Backends import tasks and runs from @bokjoy/sdk. In Python, import them with from bokjoy import tasks, runs. The names are the same, in snake case. The differences that matter are status casing, a few flags, idempotency keys, batches, schedules, delays and debounces, tags and run lists, lifecycle hooks, and the options Bok Joy does not have. The Trigger.dev side below was checked against its documentation and source on October 7, 8, 10, 11 and 13, 2026.
Triggering from your backend#
import { tasks } from '@trigger.dev/sdk'; const handle = await tasks.trigger('email.send', payload, { idempotencyKey: `order-${orderId}:receipt`,});import { tasks } from '@bokjoy/sdk'; const handle = await tasks.trigger('email.send', payload, { idempotencyKey: `order-${orderId}:receipt`,});| Trigger.dev | Bok Joy | What to change |
|---|---|---|
import { tasks, runs } from '@trigger.dev/sdk' | import { tasks, runs } from '@bokjoy/sdk' | The import. |
TRIGGER_SECRET_KEY, TRIGGER_API_URL | BOKJOY_API_KEY, BOKJOY_API_URL | The variables. The key is an environment API key, bjk_<env>_.... |
configure({ secretKey, baseURL }) | configure({ apiKey, url }) | The option names. |
tasks.trigger(id, payload, options) | tasks.trigger(id, payload, options), returning a handle with id, taskIdentifier and isCached. From @bokjoy/sdk/trigger it also has publicAccessToken, which reads that run alone for an hour, as Trigger.dev's does | Nothing, apart from the options below. |
new TriggerClient({ accessToken, baseURL, previewBranch }) | The same from @bokjoy/sdk/trigger, with Trigger.dev's key rules and handle. A Bok Joy key belongs to one environment, so previewBranch must name the key's own preview environment: a trigger that names another fails with a NotFoundError and starts nothing. The branch is never read from the environment | The import. |
tasks.trigger(id, payload) without a type argument takes any payload | The same from @bokjoy/sdk/trigger. From @bokjoy/sdk, any JSON value | Nothing. |
tasks.batchTrigger(id, items): up to 1,000 items (SDK 4.3.1 and later, 500 before), returning a batch handle with a batchId | tasks.batchTrigger(id, items): 1 to 1,000 items, all or none in one transaction, returning {runs} with every handle | Read the handles from runs. |
A batch idempotencyKey gives each item a key derived from it and the item's index | Item i gets <key>:<i> | Nothing. |
triggerAndWait only inside a task's run(). It returns {ok, id, output} or {ok: false, error}, with .unwrap() | tasks.triggerAndWait from any backend. It returns the output, and throws RunFailedError for a failed or cancelled run | Replace if (result.ok) with try/catch. Inside a task, see Waiting on child runs. |
batchTriggerAndWait | From a backend, none | Call batchTrigger, then runs.poll each run. Inside a task, see Waiting on child runs. |
runs.retrieve(id) | runs.retrieve(run) | Nothing. It takes an ID or a handle. |
A payload over 512 KB goes to object storage, and runs.retrieve returns payloadPresignedUrl and outputPresignedUrl for large values. The SDK uploads a payload over 128 KB itself. | A payload is at most 3 MiB and an output at most 10 MiB. Bok Joy stores a value over 512 KiB out of line, and runs.retrieve returns payload and output whole. There are no presigned URLs. The SDK sends the payload in the request. | Read payload and output instead of fetching a presigned URL. |
runs.list(params), with Trigger.dev's statuses and taskIdentifier | The same from @bokjoy/sdk/trigger. runs.list from @bokjoy/sdk takes Bok Joy's statuses and task | Import runs from @bokjoy/sdk/trigger. See Tags and run lists. |
runs.poll(id, { pollIntervalMs }), which gives up after 500 reads | runs.poll(run, { pollIntervalMs, timeoutMs, until, signal }), with no read limit | Set timeoutMs for a bound. |
runs.cancel(id) | runs.cancel(run), which also cancels every unfinished run below it | Nothing. |
runs.reschedule(id, { delay }) | runs.reschedule(run, { delay }). In Python, runs.reschedule(run, delay). | Nothing. See Delays and debounces for what differs. |
runs.replay(id) starts the run again from the start | No SDK call: Replay run in the console. For a failed workflow, runs.retryFromFailure(run) starts a new run that reuses the steps that succeeded before the failure and runs the rest | To run every step again, use Replay run. After fixing a failed workflow, use runs.retryFromFailure. |
runs.subscribeToRun(id) yields the run object on each change | runs.subscribe(run) yields stream messages (snapshot, event, end) for the run and every run below it | Read the run with runs.retrieve when a message says it changed. |
Machines micro, small-1x, small-2x, medium-1x, medium-2x, large-1x, large-2x | micro, small, small-2x, medium, medium-2x, large, large-2x, with the same sizes | Nothing in Node: the client and task definitions take Trigger.dev's names. In Python, rename small-1x, medium-1x and large-1x. |
Statuses and flags#
Trigger.dev's statuses are upper case. Bok Joy's are lower case, so status === 'COMPLETED' never matches. Compare with 'completed', or better, use the flags.
Code that imports runs from @bokjoy/sdk/trigger gets Trigger.dev's statuses instead. runs.retrieve, runs.poll, runs.cancel and runs.list answer with the upper case values in the first column, one for each Bok Joy status: running is EXECUTING, and failed is FAILED. Their isFailed is true for a cancelled run too, as Trigger.dev's is, and taskIdentifier names the task. The root @bokjoy/sdk keeps the lower case statuses.
| Trigger.dev status | Bok Joy status |
|---|---|
DELAYED | delayed |
QUEUED | queued |
DEQUEUED, EXECUTING | running |
WAITING | waiting |
COMPLETED | completed |
CANCELED | cancelled, with two Ls |
FAILED, CRASHED, SYSTEM_FAILURE, TIMED_OUT | failed, once its attempts are used, with the reason in error. A run past its timeout is failed at once. |
EXPIRED | None: Bok Joy has no TTL. A run no worker can hold yet has a capacityWait, and fails at its until. |
PENDING_VERSION | None: a trigger for a task the environment's deployment lacks is refused with a ValidationError. |
| Flag | In Bok Joy |
|---|---|
isCompleted | The same as Trigger.dev's: true for any finished run, failed and cancelled included. isFinished is a clearer name for it. |
isFailed | True for failed only. Trigger.dev's is also true for a cancelled run, so check isCancelled too where a cancelled run should count as failed. |
isSuccess, isCancelled, isQueued, isExecuting, isWaiting | The same names and meanings as Trigger.dev's. isQueued is true for a delayed run too. |
Python has the same names in snake case: is_success, is_cancelled and so on.
Idempotency keys#
| Trigger.dev | Bok Joy | What to change |
|---|---|---|
| Up to 2,048 characters | 1 to 128 bytes, and 124 for a batch key | Hash a longer key, for example to a 64-character SHA-256 hex digest. |
Kept for 30 days by default (idempotencyKeyTTL), then a new run can start | The same from @bokjoy/sdk/trigger, in a run and from a backend. idempotencyKeyTTL takes Trigger.dev's durations, such as "60s", "10m", "2h", "7d" or "1w", from 1 second to 365 days. tasks.trigger from @bokjoy/sdk keeps a key as long as its run, until run retention deletes it. | Nothing. |
| A run that fails releases its key, so the same key starts a new run | The same from @bokjoy/sdk/trigger. The failed run records the run that took its key (released_to). A completed or cancelled run keeps its key until its TTL passes. | Nothing. |
idempotencyKeys.reset(taskId, key, {scope, parentRunId}) lets the key start a new run | The same, with the same options. From a backend, a key that only triggers inside runs hold needs parentRunId, the run's ID, or the control plane answers 422; Trigger.dev throws there. It calls the control plane with the client's API key (BOKJOY_API_KEY or configure()), from a backend or a run. | Set BOKJOY_API_KEY where a task resets a key. |
| A trigger's handle names the run it started | An in-task trigger's handle names the first run its key started. runs.retrieve and runs.poll from @bokjoy/sdk/trigger read it as the run the key moved to, after a failed run gave the key up. | Nothing. |
A reused key returns the original run, marked isCached, whatever the payload | The same from @bokjoy/sdk/trigger and TriggerClient, batch items included. From @bokjoy/sdk, a different payload, placement, machine or queue is a ConflictError. In both, a key that already names a run of another task is a ConflictError, as Bok Joy keys are per environment and Trigger.dev's per task. | Import from @bokjoy/sdk/trigger. Never reuse a key across tasks. |
idempotencyKeys.create() scopes a key to the parent run, an attempt, or makes it global | A key is scoped to its environment. idempotencyKeys.create() makes the same SHA-256 key from the same scope. Inside a run, tasks.trigger from @bokjoy/sdk/trigger uses a key of exactly 64 characters, as every made key is, as it is: it starts one child across the environment, as in Trigger.dev. Any other key is scoped to the parent run. A wait makes it in the run's scope, as Trigger.dev does, so a child that completed is never started again by the parent's retry. | Nothing. |
Holding a key as Trigger.dev does needs a control plane and worker agents from the release that added it. Under older ones, a keyed trigger and every wait for children fail with an error that says to upgrade, before anything starts, and a trigger from a backend with a key gets a ValidationError that names the field the control plane does not take.
Options Bok Joy refuses#
Bok Joy refuses these trigger options by name, with a ValidationError, rather than ignore them:
| Trigger.dev option | Why Bok Joy refuses it | What to do |
|---|---|---|
ttl | No time-to-live | Remove it. |
maxAttempts | Attempts are part of the task's definition | Set retry: { maxAttempts } on the task, or max_attempts in the manifest. |
priority | No priorities | Remove it. |
version | Runs use the environment's current deployment | Promote the deployment you want. |
maxDuration and region are refused too, as unknown options. A run's longest attempt is its task's maxDuration. idempotencyKey, idempotencyKeyTTL and machine carry over unchanged, and so do queue and concurrencyKey, as below. metadata carries over from a backend, batch items included: it is the run's first metadata, which metadata.current() reads inside the run (not in a workflow, whose attempts rebuild their metadata as they replay), and at most 64 KiB. A trigger inside a run carries idempotencyKeyTTL and concurrencyKey too, and delay and debounce, and refuses the same options, queue, metadata, and maxDuration, region, lockToVersion and payloadType by name, before any child starts.
Delays and debounces#
delay, debounce and runs.reschedule carry over, from a backend and inside a run. See Start a run later and Debounce triggers.
| Trigger.dev | Bok Joy | What to change |
|---|---|---|
delay: '1h', a Date, or an ISO 8601 time | The same, with the same duration units | Nothing. |
A delay it cannot read starts the run at once, with no error | A ValidationError, and no run starts | Fix the delay the error names. |
| No latest time | At most the end of year 9999 | Nothing. |
runs.reschedule on a run that is not delayed is a 400 | A ConflictError (409) | Catch ConflictError if you reschedule runs that may have started. |
debounce: { key, delay, mode, maxDelay }, its key scoped to the environment and the task | The same. Python takes max_delay. | Nothing. |
| An empty debounce key | Refused: a key is 1 to 512 characters | Use a real key. |
| A trigger inside a run that a debounce folds into a run that already waits returns that run's ID | It returns the ID it made for the child, at once, before the control plane answers. That ID then names the run it joined: runs.retrieve, runs.cancel and every other call read that run with it, and its run page lists it under "Also returned as". | Nothing, unless you compare IDs: two handles from one debounce can hold different IDs for the same run. Compare runs.retrieve(id).id. |
delay and debounce on triggerAndWait and batchTriggerAndWait inside a run | Not yet: refused by name | Trigger the child with trigger, then wait for it another way, such as a workflow sleep. |
DELAYED runs take no concurrency slot | The same | Nothing. |
| A trigger folded into a debounced run records no idempotency key, so sent again with its key it counts again | The same | Nothing. |
A delayed run's idempotencyKeyTTL counts from the trigger, not from when the run starts | The same: a delay longer than the TTL frees the key before the run starts | Nothing. |
idempotencyKeys.reset on the key of the trigger that started a debounced run | The same: the run keeps waiting, and the same trigger again joins it and counts again | Nothing. |
A debounced trigger whose delay has passed is refused | The same from a backend. Inside a run, ctx.trigger refuses it at the call, by the worker's clock, because it returns the child's ID at once. One whose delay passes after the call starts at once, or joins the run that waits for its key. | Nothing. |
A delayed run runs the version deployed when it starts, unless triggered with lockToVersion | A run runs the deployment it was triggered with, however long its delay: the environment's current one from a backend, its parent's inside a run. A deploy during the delay does not change the code it runs. | To run newer code, cancel the run that waits and trigger it again after the deploy. |
Tags and run lists#
Run tags and runs.list carry over, from a backend and inside a run. Import runs from @bokjoy/sdk/trigger to keep Trigger.dev's statuses, taskIdentifier and pages. See Tag runs and List runs.
import { runs, tasks } from '@trigger.dev/sdk'; await tasks.trigger('reports.build', { orgId }, { idempotencyKey: `report-${orgId}-${month}`, tags: [`org_${orgId}`, 'monthly'],}); const page = await runs.list({ taskIdentifier: 'reports.build', tag: `org_${orgId}`, limit: 1 });const latest = page.data?.[0];const { metadata } = await runs.retrieve(latest.id); const busy = await runs.list({ status: 'EXECUTING', period: '30m', limit: 50 });import { runs, tasks } from '@bokjoy/sdk/trigger'; await tasks.trigger('reports.build', { orgId }, { idempotencyKey: `report-${orgId}-${month}`, tags: [`org_${orgId}`, 'monthly'],}); const page = await runs.list({ taskIdentifier: 'reports.build', tag: `org_${orgId}`, limit: 1 });const latest = page.data?.[0];const { metadata } = await runs.retrieve(latest.id); const busy = await runs.list({ status: 'EXECUTING', period: '30m', limit: 50 });| Trigger.dev | Bok Joy | What to change |
|---|---|---|
tags on trigger, triggerAndWait, and each item of batchTrigger and batchTriggerAndWait: up to 10 per run, each 1 to 128 characters | The same, from a backend and inside a run | Nothing. |
| A tag given twice | Kept once, where it first appears | Nothing. |
A repeated idempotencyKey returns the original run | The same, with the original run's tags, whatever tags the repeat names | Nothing. |
tags.add(tags) inside a run. Past 10 tags in all it logs an error and ignores the new tags. | The same. Outside a run it does nothing. | Nothing. |
ctx.run.tags | The run's tags when the attempt started. Tags tags.add adds show from the next attempt on. | Nothing. |
runs.list({ status, taskIdentifier, tag, from, to, period, limit, after, before }) | The same, with a list matching any of its values. Await it for a page with data, pagination, hasNextPage() and getNextPage(), or for await it for every run. | Nothing. |
limit: 25 by default, at most 100 | The same | Nothing. |
status values PENDING_VERSION, DEQUEUED, REATTEMPTING, FROZEN, CRASHED, SYSTEM_FAILURE, TIMED_OUT, EXPIRED and INTERRUPTED | Accepted, and they match no run: Bok Joy's runs are never in those states. A list that names only those is empty, and sends no request. EXECUTING matches every running run, and FAILED every failed one, crashed or timed out. | Nothing. |
The version, schedule, bulkAction, batch, region, machine, queue and error filters | Refused by name with a ValidationError | Filter by task, tag, status and time. |
isTest | true lists the runs started from the console's Test dialog, false every other run | Nothing. |
env | Accepted and ignored: an API key lists its own environment | Nothing. |
runs.list(projectRef, params), across a project's environments | Refused with a ValidationError | List each environment with its own key. |
| A tag with a comma in it | Cannot be filtered on: refused with a ValidationError | Use tags without commas where you list by them. |
createdAt, updatedAt, startedAt, finishedAt and delayedUntil are Date objects | RFC 3339 strings, in runs.list and runs.retrieve | Wrap them, as in new Date(run.createdAt). |
costInCents, baseCostInCents, durationMs | Always 0 | Do not rely on them. |
A run ID starts with run_ | A UUID | Nothing, unless your code checks the prefix. |
runs.retrieve(id).metadata | The same: what the run set with metadata, or undefined when it set nothing | Nothing. |
| List items carry no payload or output | The same: no payload, output or error. runs.retrieve has them. | Nothing. |
to | Exclusive: a run created exactly at to is left out | Add a millisecond to include it. |
period with from | Refused with a ValidationError, rather than one of them winning | Give one of them. |
tag: [] | No tag filter: every run | Leave tag out, or name at least one. |
tags.add and ctx.run.tags in lifecycle hooks | The same: hooks see and tag the run they belong to | Nothing. |
Hook runs in runs.list | Left out, unless source: 'hook' is passed to the Bok Joy client | Nothing. |
A debounced trigger in trailing mode with tags: [] | Keeps the run's tags. Only a trigger that names a tag replaces them. | Name the tags you want, or leave them. |
run.tags on the run | The same, in runs.retrieve and every page of runs.list | Nothing. |
Tagging inside a run needs a control plane and worker agents from the release that added tags. Under older ones, tags.add and every trigger with tags inside a run throw, rather than leave the run untagged.
Queues and concurrency limits#
A task's queue and Trigger.dev's queue() carry over: the same name and concurrencyLimit, with the same per-environment limit. The queue trigger option names a declared queue, as in v4, and concurrencyKey applies the limit per key. See Queues and concurrency limits.
| Trigger.dev | Bok Joy | What to change |
|---|---|---|
queue: { concurrencyLimit: 10 } on task() | The same on a task() in build.dirs, and "queue": {"concurrencyLimit": 10} in a definition you write | Nothing for a discovered task. |
queue({ name, concurrencyLimit }) from @trigger.dev/sdk | queue({ name, concurrencyLimit }) from @bokjoy/sdk or @bokjoy/sdk/trigger. In Python, pass queue={"name": ..., "concurrencyLimit": ...}. | The import. |
| Tasks that give one queue different limits: the first wins, with a warning | The deploy is refused | Give every task the same limit. |
A trigger's queue names a queue no version declares, and the run waits | A ValidationError, and no run starts | Name only declared queues. |
concurrencyLimit: 0, and pausing or overriding a queue | Not supported. A limit is 1 to 100,000. | Lower the limit and deploy. |
concurrencyKey on a trigger | The same option: the queue's limit applies per key | Nothing. |
A short wait.for keeps its slot; longer waits, triggerAndWait and batchTriggerAndWait release it | The same rule, for sleeps, waits for children and event waits | Nothing. |
Scheduled tasks#
A schedules.task keeps its code. Deploy registers its cron as the task's schedule, and schedules your backend creates keep their calls. See Schedules.
import { schedules } from '@trigger.dev/sdk'; export const digest = schedules.task({ id: 'reports.digest', cron: { pattern: '0 6 * * *', timezone: 'America/Denver' }, run: async (payload) => { // payload.timestamp is a Date },});import { schedules } from '@bokjoy/sdk/trigger'; export const digest = schedules.task({ id: 'reports.digest', cron: { pattern: '0 6 * * *', timezone: 'America/Denver' }, run: async (payload) => { // payload.timestamp is a Date },});| Trigger.dev | Bok Joy | What to change |
|---|---|---|
schedules.task({ id, cron, run }) | The same, in a folder of build.dirs | The import. |
cron: '0 * * * *' or { pattern, timezone, environments } | The same | Nothing. Deploy writes schedule: {cron, timezone, environments}, with PRODUCTION, STAGING, DEVELOPMENT and PREVIEW as prod, staging, dev and preview. |
A declared schedule without environments fires in every environment | It fires in prod only. This is on purpose: staging and previews are long-lived and run against real services. | Name environments: ['PRODUCTION', 'STAGING'] on each schedule that should fire in staging too, and add 'PREVIEW' for previews. |
| A declared schedule cannot be paused | schedules.deactivate pauses either kind, and the pause survives deploys | Nothing. |
| A tick while the previous run is unfinished queues another run | The tick is skipped, and the skip names the unfinished run | Expect skipped ticks when a run outlasts its interval. |
Schedules made in the dashboard or with schedules.create live in Trigger.dev | Bok Joy cannot read them | Export them and run the schedule import script. |
schedules.create, retrieve, list, update, activate, deactivate, del | The same names. Python has them in snake case, with delete for del. | The import. |
A deduplicationKey is unique in the project | Unique in the environment | Nothing. The same key in two environments names two schedules. |
timestamp, lastTimestamp and upcoming in the payload are Date objects | The same in a schedules.task. A plain handler gets RFC 3339 strings in UTC. | Nothing. |
Realtime in the browser#
auth.createPublicToken and useRealtimeRun carry over, with the same shapes. See Realtime in the browser.
| Trigger.dev | Bok Joy | What to change |
|---|---|---|
import { auth } from '@trigger.dev/sdk' | import { auth } from '@bokjoy/sdk'. In Python, from bokjoy import auth and auth.create_public_token. | The import. |
auth.createPublicToken({ scopes: { read: { runs: [runId] } }, expirationTime: '1h' }) | The same call, returning a bjp_... token | Nothing. |
| A token lasts 15 minutes by default, and up to 30 days | 15 minutes by default, and 24 hours at most | Mint a new token for a page that stays open longer. |
read scopes for tasks, tags and batch, and runs: true | Only read: { runs: [...] }, at most 32 runs. The others are refused with a ValidationError. | Name the runs. |
useRealtimeRun(runId, { accessToken, enabled }) from @trigger.dev/react-hooks | useRealtimeRun(runId, { accessToken, enabled }) from @bokjoy/sdk/react | The import. Add baseURL when the control plane is not https://api.bokjoy.dev. |
run.status is QUEUED, EXECUTING, COMPLETED and so on | The same upper case values. CRASHED, SYSTEM_FAILURE and TIMED_OUT come as FAILED. | Nothing. |
run.taskIdentifier, run.metadata, run.output, run.isCompleted and the other flags | The same names and meanings | Nothing. |
run.payload, run.error, run.tags, and useRealtimeRunsWithTag, useRealtimeStream and the other hooks | Not sent to the browser, and no other hooks | Read those on your server. |
Waiting on child runs#
Inside a task, triggerAndWait and batchTriggerAndWait keep Trigger.dev's results and .unwrap(). A task deploy finds is a plain task, and there a wait holds the task's process until its children finish, as on self-hosted Trigger.dev. The code before the wait runs once, so this task runs as it is, with only its import changed:
import { task } from '@trigger.dev/sdk';import { thumbnail } from './thumbnail'; export const makeThumbnails = task({ id: 'album.thumbnails', run: async ({ imageIds }) => { const { runs } = await thumbnail.batchTriggerAndWait( imageIds.map((imageId) => ({ payload: { imageId } })), ); return runs.filter((run) => run.ok).map((run) => run.output); },});import { task } from '@bokjoy/sdk/trigger';import { thumbnail } from './thumbnail'; export const makeThumbnails = task({ id: 'album.thumbnails', run: async ({ imageIds }) => { const { runs } = await thumbnail.batchTriggerAndWait( imageIds.map((imageId) => ({ payload: { imageId } })), ); return runs.filter((run) => run.ok).map((run) => run.output); },});| Trigger.dev | Bok Joy, in a plain task | What to change |
|---|---|---|
| A self-hosted task keeps its machine and queue slots while it waits, so a child in a full queue never starts | The task gives back its machine, queue and project slots while it waits, as Trigger.dev Cloud does when it checkpoints a run. A child in the parent's own concurrencyLimit: 1 queue starts. When the children finish, the task continues once its queue has room. | Nothing. |
maxDuration leaves time spent waiting out | The same. A task may be held for 24 hours in all. Past that its attempt stops and is not retried. | Nothing. |
| A task that crashes mid-wait runs again from the top | The same. A child started with an idempotencyKey is not started again: the retry waits on it. | Key each child that must run once. |
Up to 1,000 items in a batchTriggerAndWait | The same. An attempt starts at most 1,000 children in all, waits included. | Split longer lists across attempts. |
Held waits are for Node tasks deployed with an sdk folder that has them. A private worker needs an agent from the same release, or a wait throws and names the upgrade. Python tasks wait only as workflows. In a plain task has the rest.
Waiting as a workflow#
Name a task in build.workflows, beside build.dirs, and deploy registers it as a workflow. It keeps no process while it waits:
import { idempotencyKeys, task } from '@bokjoy/sdk/trigger';import { thumbnail } from './thumbnail'; export const makeThumbnails = task({ id: 'album.thumbnails', run: async ({ imageIds }) => { const { runs } = await thumbnail.batchTriggerAndWait( // Sorted, so a replay builds the same batch. [...imageIds].sort().map((imageId) => ({ payload: { imageId } })), { idempotencyKey: await idempotencyKeys.create('thumbnails') }, ); return runs.filter((run) => run.ok).map((run) => run.output); },}); // manifest.json// "build": {"dirs": ["src/trigger"], "workflows": ["album.thumbnails"]}A workflow's attempt ends at each wait and frees its machine. When the children finish, a new attempt runs the task from the top, and each wait it has passed returns its recorded results. So a task with one wait runs in two attempts, and a task with two waits runs in three.
- Code before a wait runs again in each later attempt. With one wait, it runs twice.
- A
catcharound a wait never sees the wait. An error reporter in it runs only for a real error. - A
finallyaround a wait runs once in each later attempt that gets past it. It never runs in the attempt that stops at the wait. Around the only wait, it runs once. - Open handles do not keep an attempt running. A database client or a timer is left open when the attempt ends at a wait.
A task with two waits:
export const unpause = task({ id: 'inventory.unpause', run: async ({ orgId }) => { logger.info('start'); // attempts 1, 2 and 3 try { await tasks.triggerAndWait('inventory.gate', { orgId }); // attempt 1 ends here } finally { logger.info('gate checked'); // attempts 2 and 3 } await tasks.triggerAndWait('inventory.rebuild', { orgId }); // attempt 2 ends here logger.info('done'); // attempt 3 },});Deploy checks build.workflows. Each entry must name a task that build.dirs finds, once. A task the manifest's own tasks define sets "kind": "workflow" on its entry instead. A wait's child must be a task, so a task in build.workflows cannot be the child of a wait.
| Trigger.dev | Bok Joy | What to change |
|---|---|---|
triggerAndWait and batchTriggerAndWait in any task | The same, in a task registered as a workflow. Bok Joy's own are ctx.triggerAndWait and ctx.batchTriggerAndWait. | Add the task's ID to build.workflows. In Python, await ctx.trigger_and_wait(...) and await ctx.batch_trigger_and_wait(...). |
| The task carries on from the wait | The attempt ends at the wait, and the run replays from the top when the children finish. Code before the wait runs again. | Move side effects before a wait into child tasks. |
Waits cannot run side by side, as in Promise.all | One wait at a time. Two at once fail the attempt. | Await each wait before the next, or put the children in one batch. |
| None | A replay checks each wait against history. With its default key, a wait replays only unchanged, and a changed input or list fails the attempt with an error that says to pass an idempotencyKey. With an explicit key, the recorded results stand, marked drifted: true, a batch's result adds the recorded items, and the run records a replay.drift event. | Sort a list you read from a database before a batch over it. Pass an idempotencyKey per wait in loops, and per batch over data that can change between attempts. If you pair runs with your own list, pair them with items when drifted is set. Start children for new items in a new step with a new key. |
An idempotencyKeys.create key names one run of a task in the environment | The same: a wait with a made key waits on the child of that task any run in the environment started with it. A batch key, made or not, gives each item a key made in the run's scope from it and the item's index, as on Trigger.dev, so each run's batch starts its own children. The child belongs to the run that started it. A retry from failure makes its 'run' keys from the failed run's ID (ctx.firstRunId), so it finds the children that run started. | Build your own run keys from ctx.firstRunId, not ctx.run.id, to keep them in a retry from failure. |
| When the parent retries, a wait whose child failed starts a new child | The same: on the workflow's next attempt, the steps before the first wait whose child failed replay, and that wait and every later step run again. A later wait under a key whose child completed waits on that child again. One without a key starts a new child, as every unkeyed child does when a Trigger.dev task retries. | Key each wait whose child must run once, as on Trigger.dev. |
A key made with scope: 'attempt' names a new child on each attempt | A wait refuses it, since the workflow replays its steps on a retry and the key would no longer match. trigger and batchTrigger take it. | Make the key with the run's scope, the default, or global. |
{ok: true, id, taskIdentifier, output} or {ok: false, id, taskIdentifier, error}, with .unwrap() and SubtaskUnwrapError. await triggerAndWait(...).unwrap() gives the output | The same. error is {name, message}, with the name RunFailedError or RunCancelledError. | Read the reason from error.message. |
batchTriggerAndWait gives {id, runs} | The same. id names the batch by its children; there is no batch to read with it. | Nothing, unless you read the batch by its ID. |
| A batch takes up to 1,000 items | The same: 1 to 1,000 items. Their payloads are at most 10 MiB together, and each child counts toward the run tree's limit of 10,000 triggered and batched runs by default. | Split a batch whose payloads are larger into several steps, each with its own key. |
| Each item takes the trigger options | Each item is {payload, options}, and options takes idempotencyKey, idempotencyKeyTTL, machine and concurrencyKey. The keyed items of one wait share a TTL: set it on the batch. | Remove the other item options. |
Inside a task, wait from the task. The tasks client from @bokjoy/sdk is for your backend.
Lifecycle hooks#
onStartAttempt, onStart, onSuccess, onFailure, onComplete and onCancel carry over, on a task and as tasks.onX for every task, with the same parameters. The big difference is that failure hooks also run after a crash or a timeout, in a process of their own. See Lifecycle hooks.
import { tasks } from '@trigger.dev/sdk';import { alerts } from '../lib/alerts'; tasks.onFailure('alerts', async ({ ctx, error }) => { await alerts.send(`${ctx.task.id} run ${ctx.run.id} failed: ${error.message}`);});import { tasks } from '@bokjoy/sdk/trigger';import { alerts } from '../lib/alerts'; tasks.onFailure('alerts', async ({ ctx, error }) => { await alerts.send(`${ctx.task.id} run ${ctx.run.id} failed: ${error.message}`);});| Trigger.dev | Bok Joy | What to change |
|---|---|---|
The six hooks as options of task(), schemaTask() and schedules.task() | The same | The import. |
tasks.onFailure(fn) and the others, in init.ts, in trigger.config.ts or anywhere | The same calls, in an init file or a task file in build.dirs | Move hooks from trigger.config.ts into init.ts. |
onFailure does not fire for a crashed run or a system failure | onFailure and onComplete run after every failure: a crash, an out-of-memory kill, a maxDuration timeout and a lost worker too | Expect failure hooks for runs that used to end without them. |
| Every hook runs in the run's process | onFailure, onComplete after a failure, and onCancel run in a new process once the run has ended | Read what a failure hook needs from payload, ctx and error, or set it up in init.ts. A closure or a variable the run set is not there. |
onCancel runs while the run is still executing, with up to 30 seconds to await runPromise | onCancel runs after the run's process has been ended, and runPromise is already settled | Clean up after the run in onCancel. It cannot stop work in progress. |
onFailure gets the error object the task threw | A copy rebuilt in the hook's process: the standard error classes, AbortTaskRunError, the name, message, stack and the error's codes and statuses such as code and status. Other fields, which can hold request headers or row values, are left out. Another class arrives as an Error with its name | Check error.name rather than instanceof for your own error classes, and error.code rather than nested fields. |
| A hook runs once | A hook runs at least once: a hook run whose worker is lost runs its hooks again | Make hooks safe to run twice, for example by keying what they send with ctx.run.id. |
| A hook registered only when an environment variable is set | Deploy finds hooks without your variables, so it misses that one, and it never runs after a failure or cancel | Register hooks every time, and check the variable inside the hook. |
Errors thrown in onSuccess, onFailure and onComplete are ignored, and shown in the dashboard | The same: shown in the run's Lifecycle hooks panel | Nothing. |
onWait, onResume, catchError, middleware, locals, and the deprecated init, cleanup and handleError | Not yet. Deploy refuses each with its file and line. | Remove them. Run setup at the top of init.ts. |
Not in Bok Joy yet#
batchTriggerAndWaitfrom a backend, as above.- Batches across tasks.
batch.triggerAndWaitandbatch.triggerByTaskAndWait, with a task per item. A Bok Joy batch starts children of one task, so run one batch per task. onWait,onResume,catchError,middlewareandlocals, on a task or ininit.ts, and the deprecatedinit,cleanupandhandleError. The other lifecycle hooks carry over.- TTLs.
Deploy refuses each of these with the file and line, and a task that calls one fails with an error that names it, so nothing runs without the behavior it asked for.
Deploying a Trigger.dev project#
A project laid out for Trigger.dev deploys without moving files. Your trigger.config.ts settings move into the manifest, and the tasks keep their imports of ../../lib, @/ paths and JSON. See Bundle a TypeScript project and Find tasks in folders.
trigger.config.ts | Bok Joy manifest | What to change |
|---|---|---|
dirs: ['./src/trigger'] | build.dirs: ["src/trigger"] | Nothing. Deploy finds the tasks each file exports. |
| None | build.workflows: ["album.thumbnails"] | Optional. List a task that should wait as a workflow, freeing its machine. See Waiting as a workflow. |
src/trigger/init.ts | Loaded before every task, in each folder of build.dirs, and before a task's failure hooks | Nothing. Keep setup such as Sentry.init() and tasks.onFailure there. |
import ... from '@trigger.dev/sdk' | import ... from '@bokjoy/sdk/trigger' | The import. Deploy refuses a file that still imports @trigger.dev/*, with its line. |
build.external | build.external | Nothing. |
prismaExtension({ schema, mode: 'legacy' }) | build.prisma: {schema, mode: "legacy"} | Nothing. Bok Joy generates the client in the image, for the image's platform. |
legacy-peer-deps=true in .npmrc | dependencies.node.legacy_peer_deps: true | Add it beside your lockfile. |
aptGet({ packages }) | dependencies.apt | Nothing. See System packages. |
ffmpeg() | dependencies.apt: ["ffmpeg"] | Debian's ffmpeg, on PATH. Set FFMPEG_PATH and FFPROBE_PATH as variables if your code reads them. ffmpeg({ version }) has no equivalent. |
puppeteer() | dependencies.apt: ["chromium", "fonts-liberation"] | Launch /usr/bin/chromium with --no-sandbox, for example by setting the variable PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium. |
syncEnvVars(...) | None | Set each variable with the CLI, as below. |
maxDuration | defaults.timeout_ms, in milliseconds, up to 24 hours | Multiply by 1,000. A task's own maxDuration replaces it. Without either, an attempt gets 30 seconds. |
retries.default | defaults.retry, with the same fields | Move it. A task's own retry replaces it as a whole. Without either, a task gets 3 attempts. |
onStartAttempt, onSuccess, onFailure and the other hooks | tasks.onStartAttempt and the others in init.ts | Move them into init.ts, as tasks.onFailure(fn) and so on. |
runtime: 'node' | "runtime": "node" on each task | Nothing. |
project | None | Remove it. Each Bok Joy project has its own environments, and deploy names the project. |
Bok Joy has no syncEnvVars. Set the variables once per environment from a shell where they are set, reading each value from standard input:
for name in SIMPHONY_SFTP_HOST SIMPHONY_SFTP_USER SIMPHONY_SFTP_PASSWORD; do printenv "$name" > /dev/null || continue printenv "$name" | durable-compute variables set "$name" --env proddoneprintenv fails for a name that is not set, so the loop skips it, as syncEnvVars skips a missing value. Without that check, variables set would store an empty value. See Variables.
Convert a project with the codemod#
The Bok Joy checkout has a codemod for a Trigger.dev v4 project. Run it with --dry-run first, and read its report:
node /path/to/bokjoy/scripts/trigger-codemod/index.mjs <project root> --dry-runnode /path/to/bokjoy/scripts/trigger-codemod/index.mjs <project root>- It rewrites the imports in every
.ts,.tsx,.js,.jsx,.mjsand.cjsfile.@trigger.dev/sdkand@trigger.dev/sdk/v3become@bokjoy/sdk/trigger, and@trigger.dev/react-hooksbecomes@bokjoy/sdk/react. Imports, re-exports,import(),require()and jest or vitest mocks all change. - It writes the manifest. It runs
trigger.config.tsand writesbokjoy.manifest.jsonbeside it, with the settings mapped as the table above maps them. It never changes the config. Delete it once the move is done. - It copies the SDK from the checkout into
sdk/nodein your project, which deploy bundles. Pass--no-vendor-sdkto skip it. - It reports what it could not convert, such as an extension with no equivalent or a name the SDK does not export. It also lists code that deploys but behaves differently, such as a batch over 1,000 items.
--json <file>writes the report as JSON too.
It never edits package.json, the lockfile or tsconfig.json. The config runs in a child Node process that can read only your project and the codemod, and cannot write files, open a network connection or start a process.
Import dashboard schedules#
Schedules made in Trigger.dev's dashboard, or with schedules.create, live only in Trigger.dev. The schedule import script in the checkout makes them again on Bok Joy. First export them, once per Trigger.dev environment: save the answer of schedules.list() as a JSON file. The script never calls Trigger.dev.
# A dry run, the default: it reads the environment's schedules, prints the plan and writes nothing.BOKJOY_API_URL=https://api.bokjoy.dev BOKJOY_API_KEY=bjk_staging_... \ node /path/to/bokjoy/scripts/import-trigger-schedules/index.mjs staging-schedules.json --trigger-env STAGING# The same with --apply makes the changes.BOKJOY_API_URL=https://api.bokjoy.dev BOKJOY_API_KEY=bjk_staging_... \ node /path/to/bokjoy/scripts/import-trigger-schedules/index.mjs staging-schedules.json --trigger-env STAGING --apply- The schedules go to the API key's environment. Deploy first: each schedule's task must be in the environment's current deployment.
- Running it again changes nothing twice. Each schedule keeps its cron, time zone and external ID, and its deduplication key, or
trigger:<schedule id>without one. A schedule whose cron, time zone, task or external ID changed is updated in place.--task-map old=newrenames a task. - Paused schedules are skipped, unless you pass
--include-inactive: then each is made and paused at once. A schedule you paused on Bok Joy stays paused, unless you pass--sync-active. - Declared schedules are skipped, since deploy makes them from your code.
- It checks before it sends. A schedule Bok Joy would refuse is skipped and reported: a cron with seconds, a nickname such as
@hourly, orL,W,#or?, and a key or external ID over 128 bytes. An import that would take the environment past 1,000 schedules sends nothing. - A schedule Bok Joy refuses anyway, such as one whose task the current deployment lacks, is reported. The rest still import, and the script exits with 1.
Defining tasks#
A task file keeps its definitions. Change the import, and name the folder in build.dirs:
import { task } from '@trigger.dev/sdk'; export const sendEmail = task({ id: 'email.send', machine: 'small-1x', retry: { maxAttempts: 5 }, run: async (payload, { ctx }) => { // ... },});import { task } from '@bokjoy/sdk/trigger'; export const sendEmail = task({ id: 'email.send', machine: 'small-1x', retry: { maxAttempts: 5 }, run: async (payload, { ctx }) => { // ... },});| Trigger.dev | Bok Joy | What to change |
|---|---|---|
task({ id, run, machine, maxDuration, retry, queue }) | The same | The import. See Queues and concurrency limits. |
schemaTask({ id, schema, run }) | The same, with zod or any parser | The import. |
schedules.task({ id, cron, run }) | The same | The import. See Scheduled tasks. |
retry: { maxAttempts, factor, minTimeoutInMs, maxTimeoutInMs, randomize } | The same fields, defaults and backoff | Nothing. Python's define_task takes the fields in snake case. |
maxDuration, in seconds | The same, up to 24 hours | Nothing. |
A run past maxDuration fails without a retry | The same: an attempt whose handler runs past its maxDuration is stopped, and the run fails without a retry | Nothing. |
A thrown error is not retried unless retries.default or the task's retry is set | A failed attempt retries until its attempts are used (3 unless set), with Trigger.dev's backoff | Set retry: { maxAttempts: 1 } on a task that must never retry. |
throw new AbortTaskRunError(message) | The same, imported from @bokjoy/sdk/trigger. In Python, from bokjoy import AbortTaskRunError. | The import. An error named AbortTaskRunError from Trigger.dev's SDK also works. |
retry: { outOfMemory: { machine: 'large-1x' } } | The same: an attempt that runs out of memory moves the run to that machine, with Trigger.dev's backoff, counting against maxAttempts. Without it, the run fails at once. See Out of memory. | Nothing. |
throw new OutOfMemoryError() | The same, imported from @bokjoy/sdk/trigger. In Python, from bokjoy import OutOfMemoryError, and Python's MemoryError counts too. Another Python library's error of that name, such as the Redis client's, does not. | The import. An error named OutOfMemoryError from Trigger.dev's SDK also works. |
An attempt killed with SIGKILL counts as out of memory | Only an attempt the kernel stopped for its own memory counts. An attempt stopped because another on its machine used more than it reserved, and a kill -9 for another reason, are ordinary failures and are retried. When Bok Joy is less sure, such as when a process the task started was stopped, the run still moves to retry.outOfMemory.machine but never fails without one. See How it is detected. | Nothing. A task that ends a child process for memory itself should throw OutOfMemoryError. |
ctx.machine, with name, cpu and memory | The same, with Trigger.dev's names, plus cpuMillis and memoryMib | Nothing. |
run(payload, { ctx }), with ctx.run, ctx.task, ctx.attempt and ctx.environment | The same fields. ctx.environment has the environment's slug, its type, such as PRODUCTION, and Bok Joy's kind, such as production. Bok Joy's own context is ctx.bokjoy. | Nothing. |
A Date in a task's output arrives as a Date | It arrives as its ISO 8601 string, as JSON.stringify writes it | Wrap it, as in new Date(run.output.sentAt). |
metadata.set, get, current, increment, decrement, append | The same, kept with the run. A retry reads what earlier attempts stored. Values go as JSON: an undefined field is left out and a Date becomes its ISO string. | Nothing. del, replace, remove and streams are refused. |
logger.info and its levels | The same, one line per call in the attempt's logs | Nothing. |
tags.add and ctx.run.tags | The same. See Tags and run lists. | Nothing. |
tasks.trigger, myTask.trigger and batchTrigger inside a run | The same, and the child is linked to the run. Payloads go as JSON, as Trigger.dev sends them: an undefined field is left out and a Date becomes its ISO string. NaN, Infinity, a BigInt or a cycle fails the trigger. A batch starts all of its children or none. | Nothing, apart from the options refused above. |
triggerAndWait and batchTriggerAndWait inside a run | The same results. In a plain task the wait holds the task until its children finish, as on self-hosted Trigger.dev. In a task registered as a workflow the attempt ends at the wait. | Nothing. See Waiting on child runs. |
onStartAttempt, onStart, onSuccess, onFailure, onComplete, onCancel | The same. onFailure, onComplete after a failure, and onCancel run in a process of their own. | Nothing, apart from what Lifecycle hooks lists. |
onWait, onResume, catchError, middleware, locals, init, cleanup, handleError | Not yet. Deploy refuses each with its file and line. | Remove them. |
Tasks has the full mapping of options to manifest fields. A task can also be a plain exported function registered by hand in the manifest, with the same retry and compute.timeout_ms in its definition, and both kinds can sit in one project.
Long waits belong in a workflow, whose sleeps, event waits and waits for children hold no worker.