This document describes the API for defining tasks in the Trigger.dev SDK. It covers the three main task definition functions (task(), schemaTask(), and toolTask()), their configuration options, and the resulting task objects that can be triggered and managed.
For information about triggering tasks and scheduling executions, see Task Triggering and Scheduling.
For information about lifecycle hooks that execute during task runs, see Lifecycle Hooks.
For information about build-time customization of the task runtime, see Build Extensions.
The SDK provides three functions for defining tasks, each serving a different use case. All three functions return a Task object with methods for triggering, batching, and managing task runs.
task() FunctionThe task() function is the primary way to define a task. It accepts a TaskOptions object and returns a Task object.
Basic Signature:
Task Object Methods:
trigger(payload, options) - Enqueues a task runbatchTrigger(items, options) - Enqueues multiple runstriggerAndWait(payload, options) - Enqueues and waits for completionbatchTriggerAndWait(items, options) - Enqueues multiple and waits for allSources: packages/trigger-sdk/src/v3/shared.ts138-161 packages/core/src/v3/types/tasks.ts100-180
schemaTask() FunctionThe schemaTask() function is used when you want to define a task with runtime payload validation using Zod schemas. This is useful for tasks that will be triggered externally or when you want strong runtime type safety.
Key Difference: When payloadSchema is provided, the payload type becomes any at the call site (TypeScript doesn't validate), but runtime validation is performed before the task executes.
Sources: packages/trigger-sdk/src/v3/shared.ts279-318 packages/core/src/v3/types/tasks.ts182-236
toolTask() FunctionThe toolTask() function creates tasks compatible with the AI SDK's tool system. These tasks can be used as tools in AI agent workflows.
Deprecated Note: The toolTask() function is deprecated in favor of ai.tool(mySchemaTask) pattern introduced in SDK v5 support.
Sources: packages/trigger-sdk/src/v3/shared.ts320-374 packages/core/src/v3/types/tasks.ts238-284
Sources: packages/trigger-sdk/src/v3/shared.ts138-210 packages/core/src/v3/resource-catalog-api.ts1-50
The TaskOptions interface defines the configuration for a task:
| Option | Type | Required | Description |
|---|---|---|---|
id | string | Yes | Unique identifier for the task |
run | function | Yes | The main execution function |
retry | RetryOptions | No | Retry configuration |
queue | Queue | No | Queue assignment |
machine | MachinePreset | No | Compute resource preset |
maxDuration | number | No | Maximum execution time in seconds |
description | string | No | Human-readable description |
jsonSchema | JSONSchema | No | JSON schema for the payload |
Sources: packages/core/src/v3/types/tasks.ts100-180
The id field must be a unique string that identifies the task within your project. It is used for:
Sources: packages/trigger-sdk/src/v3/shared.ts163
run FunctionThe run function is the core execution logic of the task. It receives the payload and a RunFnParams object:
RunFnParams Properties:
ctx: TaskRunContext - Context about the current runinit: TInitOutput - Output from init hookssignal: AbortSignal - Cancellation signalSources: packages/core/src/v3/types/tasks.ts41-47 packages/core/src/v3/schemas/common.ts300-350
The retry option configures automatic retry behavior:
Retry Behavior:
maxAttempts timesminTimeout * (factor ^ attemptNumber)maxTimeoutInMsSources: packages/core/src/v3/schemas/common.ts157-174 packages/core/src/v3/utils/retries.ts1-100
The queue option assigns a task to a named queue with concurrency limits:
Queue Registration: The queue() function registers queue metadata in the resourceCatalog, which is used during task indexing to generate the WorkerManifest.
Sources: packages/trigger-sdk/src/v3/shared.ts124-131 packages/core/src/v3/schemas/common.ts175-200
The machine option specifies compute resources for task execution:
Available Presets:
"micro" - 0.25 vCPU, 0.5 GB RAM"small-1x" - 1 vCPU, 1 GB RAM (default)"small-2x" - 1 vCPU, 2 GB RAM"medium-1x" - 2 vCPU, 4 GB RAM"large-1x" - 4 vCPU, 8 GB RAM"large-2x" - 4 vCPU, 16 GB RAMSources: packages/core/src/v3/schemas/common.ts230-270
When a task is defined, its metadata is registered in the resourceCatalog, which is a global singleton that collects all task and queue definitions during module loading.
Sources: packages/trigger-sdk/src/v3/shared.ts162-210 packages/core/src/v3/resource-catalog-api.ts1-100
Internally, tasks are represented as TaskMetadataWithFunctions objects that contain both metadata and executable functions:
Key Fields:
id - The task identifierfns - Object containing all executable functions (run, hooks, error handlers)retry - Retry configurationqueue - Queue metadatamachine - Machine presetSources: packages/core/src/v3/types/index.ts50-100
For tasks defined with schemaTask(), payload validation occurs before task execution:
Error Handling: Schema validation errors result in a TASK_INPUT_ERROR with skipRetrying: true, preventing infinite retries for invalid payloads.
Sources: packages/core/src/v3/workers/taskExecutor.ts116-144 packages/core/src/v3/errors.ts150-200
During the build/deploy process, the CLI executes an indexing phase that discovers all tasks:
WorkerManifest Structure:
Sources: packages/cli-v3/src/workers/dev/index-worker.ts1-200 packages/core/src/v3/schemas/build.ts1-150
The Task object returned by task(), schemaTask(), and toolTask() provides the following methods:
Enqueues a task run without waiting for completion.
Returns: A RunHandle with id and metadata about the enqueued run.
Sources: packages/trigger-sdk/src/v3/shared.ts166-176
Enqueues multiple task runs in a single API call.
Returns: A BatchRunHandle with batchId and runs array.
Sources: packages/trigger-sdk/src/v3/shared.ts177-187
Enqueues a task run and waits for it to complete.
Returns: A TaskRunResult with either { ok: true, output } or { ok: false, error }.
Sources: packages/trigger-sdk/src/v3/shared.ts188-198
Enqueues multiple task runs and waits for all to complete.
Returns: A BatchResult with a runs array of results.
Sources: packages/trigger-sdk/src/v3/shared.ts199-209
Tasks can include lifecycle hooks directly in their definition or register them globally. The following hooks are supported:
| Hook | Phase | Purpose |
|---|---|---|
init | Before first attempt | Initialize resources |
onStart | Before first attempt | First-time setup (deprecated) |
onStartAttempt | Before each attempt | Per-attempt setup |
middleware | Around run function | Wrap execution |
onSuccess | After success | Handle success |
onFailure | After failure | Handle failure |
onComplete | After finish | Cleanup (success or failure) |
cleanup | After all hooks | Final cleanup |
onWait | When suspending | Handle suspension |
onResume | When resuming | Handle resumption |
onCancel | When canceled | Handle cancellation |
handleError | On error | Custom error handling |
Registration in Task Definition:
Sources: packages/core/src/v3/types/tasks.ts100-180 packages/core/src/v3/lifecycleHooks/types.ts1-200
The TaskRunContext object provides information about the current run:
Accessing Context: The context is available in the run function's second parameter and in all lifecycle hooks.
Sources: packages/core/src/v3/schemas/common.ts300-400
Task execution errors are classified by error codes defined in TaskRunErrorCodes:
| Error Code | Description | Retryable |
|---|---|---|
TASK_INPUT_ERROR | Payload validation failed | No |
TASK_OUTPUT_ERROR | Output serialization failed | No |
TASK_EXECUTION_ERROR | User code threw error | Yes |
TASK_MIDDLEWARE_ERROR | Middleware threw error | No |
INTERNAL_ERROR | System error | Yes |
HANDLE_ERROR_ERROR | Error handler threw error | No |
Error Flow:
run() functionhandleError hook (if defined) processes errorTaskExecutor determines if retry should occuronFailure hook called if not retryingonComplete hook called with error resultSources: packages/core/src/v3/schemas/common.ts450-500 packages/core/src/v3/workers/taskExecutor.ts199-247
The Task Definition API provides three functions for defining tasks:
task() for standard tasks with TypeScript typesschemaTask() for tasks with runtime schema validationtoolTask() for AI SDK tool integrationTasks are configured via TaskOptions and registered in the resourceCatalog for indexing during build/deploy. The resulting Task object provides methods for triggering, batching, and waiting for task executions.
Sources: packages/trigger-sdk/src/v3/shared.ts1-600 packages/trigger-sdk/src/v3/tasks.ts1-100 packages/core/src/v3/types/tasks.ts1-400
Refresh this wiki
This wiki was recently refreshed. Please wait 7 days to refresh again.