This document describes the Task Definition API provided by @trigger.dev/sdk, which allows developers to define executable background tasks with configurable properties including retry policies, queue assignments, machine resources, and lifecycle hooks. The API consists of three main functions: task(), schemaTask(), and toolTask() (deprecated).
For information about triggering and scheduling tasks after they are defined, see Task Triggering and Scheduling. For details on lifecycle hooks configuration, see Lifecycle Hooks.
The SDK exposes three functions for creating tasks, all located in packages/trigger-sdk/src/v3/shared.ts141-287:
The primary function for creating tasks without explicit schema validation. It accepts either TaskOptions or TaskOptionsWithSchema and returns a Task object.
Function Signatures:
The function performs three key operations:
Sources: packages/trigger-sdk/src/v3/shared.ts141-258 packages/trigger-sdk/src/v3/tasks.ts89
Creates a task with schema-based payload validation. The schema can be any object with a parse() or parseAsync() method (e.g., Zod schemas, Yup schemas).
The function wraps the standard task creation with schema parsing logic packages/trigger-sdk/src/v3/shared.ts289-335:
Sources: packages/trigger-sdk/src/v3/shared.ts289-335 packages/trigger-sdk/src/v3/tasks.ts91
Note: This function is deprecated. Use ai.tool() instead (see AI Integration).
Creates a task compatible with AI SDK tools by converting tool parameters to a schema:
Internally calls schemaTask() with converted parameters packages/trigger-sdk/src/v3/shared.ts260-286
Sources: packages/trigger-sdk/src/v3/shared.ts260-286 packages/trigger-sdk/src/v3/tasks.ts93
Required Properties:
id: Unique task identifier used for triggering and indexing packages/trigger-sdk/src/v3/shared.ts169run: Async function containing the task execution logic packages/trigger-sdk/src/v3/shared.ts241Optional Properties:
description: Human-readable description displayed in the dashboard packages/trigger-sdk/src/v3/shared.ts170-234jsonSchema: JSON schema representation for task indexing packages/trigger-sdk/src/v3/shared.ts171-238Sources: packages/core/src/v3/types/tasks.ts203-236 packages/trigger-sdk/src/v3/shared.ts164-168
Tasks can be assigned to named queues with concurrency limits:
| Property | Type | Description |
|---|---|---|
queue | Queue | { name: string } | Queue assignment for the task |
queue.name | string | Queue identifier |
queue.concurrencyLimit | number (optional) | Max concurrent runs in this queue |
Queues are created using the queue() function packages/trigger-sdk/src/v3/shared.ts131-138 and registered in the resource catalog packages/trigger-sdk/src/v3/shared.ts247-251
Sources: packages/trigger-sdk/src/v3/shared.ts131-251 packages/core/src/v3/types/tasks.ts207-208
| Property | Type | Default | Description |
|---|---|---|---|
retry.maxAttempts | number | 3 | Maximum retry attempts |
retry.minTimeoutInMs | number | 1000 | Initial retry delay |
retry.maxTimeoutInMs | number | 60000 | Maximum retry delay |
retry.factor | number | 2 | Exponential backoff factor |
retry.randomize | boolean | false | Add jitter to delays |
The retry configuration is merged with default options packages/trigger-sdk/src/v3/shared.ts236 and used by the task executor during error handling packages/core/src/v3/workers/taskExecutor.ts710-745
Sources: packages/core/src/v3/types/tasks.ts209-210 packages/trigger-sdk/src/v3/shared.ts236
Tasks can specify compute resources using presets or custom configurations:
Machine configuration is registered in task metadata packages/trigger-sdk/src/v3/shared.ts237 and affects worker pod resource allocation (see Worker Execution).
Sources: packages/core/src/v3/types/tasks.ts211-212 packages/trigger-sdk/src/v3/shared.ts237
maxDuration: Maximum execution time in seconds before the task is forcibly terminated packages/core/src/v3/types/tasks.ts213
Enforced by killing the worker process packages/core/src/v3/workers/taskExecutor.ts427-428 when the limit is exceeded.
Sources: packages/core/src/v3/types/tasks.ts213 packages/trigger-sdk/src/v3/shared.ts238
Tasks can define functions that execute at specific points in the task lifecycle:
| Hook | Execution Point | Purpose |
|---|---|---|
onInit | Before first attempt | Initialize resources, return init output |
onStart | Before first attempt (deprecated) | Use onStartAttempt instead |
onStartAttempt | Before each attempt | Setup per-attempt resources |
onSuccess | After successful run | Cleanup, notifications |
onFailure | After final failure | Error handling, alerts |
onComplete | After any completion | Guaranteed cleanup |
onWait | When run enters wait state | Handle suspension |
onResume | When run resumes from wait | Handle restoration |
onCancel | When run is canceled | Cancel operations |
handleError | On error occurrence | Custom error handling, retry decisions |
middleware | Wraps run execution | Cross-cutting concerns |
cleanup | After all hooks | Final cleanup |
Hooks are registered via registerTaskLifecycleHooks() packages/trigger-sdk/src/v3/shared.ts230 and executed by the TaskExecutor packages/core/src/v3/workers/taskExecutor.ts148-227
Sources: packages/core/src/v3/types/tasks.ts214-232 packages/trigger-sdk/src/v3/shared.ts230
Each method accepts different parameters:
(payload: TInput, options?: TriggerOptions)Promise<RunHandle<TIdentifier, TOutput>>(items: BatchItem<TInput>[], options?: BatchTriggerOptions)Promise<BatchRunHandle<TIdentifier, TOutput>>(payload: TInput, options?: TriggerAndWaitOptions, requestOptions?: ApiRequestOptions)TaskRunPromise<TIdentifier, TOutput>unwrap() method(items: BatchTriggerAndWaitItem<TInput>[], options?: BatchTriggerAndWaitOptions)Promise<TaskRunResult<TOutput>[]>Sources: packages/trigger-sdk/src/v3/shared.ts169-228 packages/core/src/v3/types/tasks.ts239-271
The registration process ensures that:
The resourceCatalog is a global registry packages/core/src/v3/workers/resourceCatalog.ts used by:
Sources: packages/trigger-sdk/src/v3/shared.ts230-251 packages/core/src/v3/workers/resourceCatalog.ts
The task definition API uses TypeScript generics to maintain type safety through the entire execution flow:
Task Definition: Generic parameters TIdentifier, TInput, TOutput flow from TaskOptions to Task packages/trigger-sdk/src/v3/shared.ts151-168
Payload Validation: When using schemaTask(), the schema's inferred type becomes TInput packages/trigger-sdk/src/v3/shared.ts289-303
Trigger Methods: Return types include the generic parameters:
trigger() returns RunHandle<TIdentifier, TOutput> packages/trigger-sdk/src/v3/shared.ts173triggerAndWait() returns TaskRunPromise<TIdentifier, TOutput> packages/trigger-sdk/src/v3/shared.ts196Result Extraction: The output type flows through to result objects packages/core/src/v3/types/tasks.ts273-281
| Type | Purpose | Location |
|---|---|---|
TaskOptions<TId, TIn, TOut> | Task configuration | packages/core/src/v3/types/tasks.ts203-236 |
Task<TId, TIn, TOut> | Task object with methods | packages/core/src/v3/types/tasks.ts239-271 |
RunHandle<TId, TOut> | Handle to triggered run | packages/core/src/v3/types/tasks.ts306-343 |
TaskRunResult<TOut> | Discriminated union result | packages/core/src/v3/types/tasks.ts273-281 |
TaskRunPromise<TId, TOut> | Promise with unwrap() | packages/core/src/v3/types/tasks.ts345-356 |
Sources: packages/core/src/v3/types/tasks.ts203-356 packages/trigger-sdk/src/v3/shared.ts141-335
A complete task definition example from the reference project:
This example demonstrates:
onStart) usageSources: references/hello-world/src/trigger/example.ts6-55
The task metadata registered during task definition is consumed by the TaskExecutor during runtime:
Task Loading: Worker processes load task functions from the resource catalog packages/cli-v3/src/entryPoints/dev-run-worker.ts19
Execution Context: The TaskExecutor wraps task execution with tracing, logging, and error handling packages/core/src/v3/workers/taskExecutor.ts66-89
Lifecycle Hook Execution: Hooks registered during task definition are invoked at appropriate points packages/core/src/v3/workers/taskExecutor.ts179-227
Retry Logic: Retry configuration influences error handling decisions packages/core/src/v3/workers/taskExecutor.ts710-745
For details on task execution mechanics, see Worker Execution.
Refresh this wiki
This wiki was recently refreshed. Please wait 4 days to refresh again.