This page documents the Task Definition API, which provides functions and types for defining background tasks in Trigger.dev. It covers the task() and schedules.task() functions, their configuration options including schemas, retry logic, queue settings, machine presets, and execution constraints.
For information about triggering tasks after they are defined, see Task Triggering and Scheduling. For details on lifecycle hooks that can be attached to tasks, see Lifecycle Hooks.
Trigger.dev exports task definition functions from @trigger.dev/sdk/v3 (packages/trigger-sdk/src/v3/index.ts):
| Function | Export Path | Use Case | Type Safety | Schema Support |
|---|---|---|---|---|
task() | @trigger.dev/sdk/v3 | General-purpose tasks | TypeScript inference from run function | Optional jsonSchema parameter |
schemaTask() | @trigger.dev/sdk/v3 | Tasks requiring Zod schema validation | Full Zod type inference | Required Zod schema |
toolTask() | N/A | Deprecated - Use ai.tool() instead | N/A | N/A |
Sources: packages/trigger-sdk/package.json24-27 packages/trigger-sdk/CHANGELOG.md24-25 packages/trigger-sdk/CHANGELOG.md260-261
Sources: packages/trigger-sdk/package.json24-27 packages/core/package.json52-53
The task() function is the general-purpose task definition API exported from @trigger.dev/sdk/v3. It infers TypeScript types from the run function signature and returns a Task<TPayload, TOutput> object with trigger methods.
Export Location: packages/trigger-sdk/package.json24-27 defines the export from ./src/v3/index.ts
| Parameter | Type | Required | Description |
|---|---|---|---|
id | string | Yes | Unique identifier for the task within the project |
run | (payload: TInput, ctx: TaskContext) => Promise<TOutput> | Yes | The main execution function |
init | (payload: TInput, ctx: TaskContext) => Promise<void> | No | Pre-execution initialization function |
jsonSchema | JSONSchema | No | JSON Schema for payload type definition |
retry | RetryOptions | No | Retry behavior configuration |
queue | QueueOptions | No | Queue assignment and concurrency settings |
machine | MachinePreset | No | Compute resource allocation preset |
maxDuration | number | No | Maximum execution time in seconds |
onStartAttempt | function | No | Hook called before each attempt starts |
onSuccess | function | No | Hook called on successful completion |
onFailure | function | No | Hook called on failure after all retries |
onComplete | function | No | Hook called on completion (success or failure) |
Lifecycle Hook Changes (v4.1.0):
onStart deprecated - only fired before first attemptonStartAttempt added - fires before every attempt (including retries)onCancel added (v4.0.0-v4-beta.12) - fires when a run is cancelledTo replicate old onStart behavior with onStartAttempt:
Sources: packages/trigger-sdk/CHANGELOG.md48-83 packages/trigger-sdk/CHANGELOG.md304 packages/trigger-sdk/CHANGELOG.md589
The schemaTask() function provides enhanced type safety through Zod schema validation. It automatically validates payloads at runtime and infers TypeScript types from the schema at compile-time.
Export Location:
./src/v3/index.ts@trigger.dev/core/v3 to prevent TypeScript error TS2742Type Re-export Fix (v4.2.0):
The schemaTask types are re-exported from @trigger.dev/core/v3 to prevent the TypeScript error "TS2742: The inferred type of 'task' cannot be named without a reference to '@trigger.dev/core/v3'."
Sources: packages/trigger-sdk/CHANGELOG.md24-25 packages/core/package.json29
Sources: packages/trigger-sdk/CHANGELOG.md24-25
The id field is the only required configuration besides run. It must be unique within your project and is used to:
Task IDs support non-URL-friendly characters, but kebab-case or snake_case is recommended for consistency.
Sources: packages/trigger-sdk/CHANGELOG.md580
The run function contains the task's main execution logic. It receives two arguments:
Location: Defined in task configuration, executed by packages/core/src/v3/workers/taskExecutor.ts
Sources: packages/core/src/v3/workers/taskExecutor.ts packages/trigger-sdk/CHANGELOG.md217-230
The ctx parameter (type: TaskContext) provides runtime information and utilities:
| Property | Type | Added | Description |
|---|---|---|---|
ctx.run.id | string | - | Unique identifier for this run |
ctx.run.attempt.number | number | - | Current attempt number (starts at 1) |
ctx.run.createdAt | Date | - | Timestamp when run was created |
ctx.run.startedAt | Date | - | Timestamp when run started executing |
ctx.run.parentTaskRunId | string | undefined | v4.0.0-beta.26 | Parent run ID if triggered by another task |
ctx.run.rootTaskRunId | string | undefined | v4.0.0-beta.26 | Root run ID in the execution tree |
ctx.run.version | string | v4.0.0-beta.0 | Task version from deployment |
ctx.task.id | string | - | The task's ID |
ctx.environment.id | string | - | Environment ID |
ctx.environment.type | string | - | Environment type (PRODUCTION, STAGING, DEVELOPMENT) |
ctx.deployment.id | string | v4.0.0-beta.26 | Deployment ID |
ctx.deployment.version | string | v4.0.0-beta.26 | Deployment version string |
Hierarchical Task Relationships (v4.0.0-beta.26):
The parentTaskRunId and rootTaskRunId properties support parent/child task relationships. For root runs (no parent), these properties work with metadata.root and metadata.parent:
Sources: packages/trigger-sdk/CHANGELOG.md427-440 packages/trigger-sdk/CHANGELOG.md603 packages/core/package.json29
The init function is an optional pre-execution hook that runs before the run function. It's useful for:
Key Characteristics:
run()payload and ctx as run()onStartAttempt lifecycle hook (which runs before every retry attempt)Sources: Based on task configuration patterns in the SDK
Sources: packages/trigger-sdk/CHANGELOG.md14-15 packages/trigger-sdk/CHANGELOG.md389
The simplest approach for tasks with well-defined internal types:
Sources: packages/trigger-sdk/src/v3/index.ts
For tasks that accept external input or require validation, use schemaTask():
Benefits:
Sources: packages/trigger-sdk/CHANGELOG.md14-15 packages/core/src/v3/index.ts
For integration with systems that use JSON Schema or non-Zod workflows:
Note: JSON Schema support is primarily used for AI SDK integration via ai.tool() (see AI Tool Integration section).
Sources: packages/trigger-sdk/CHANGELOG.md389 packages/trigger-sdk/CHANGELOG.md215
Tasks can be configured to automatically retry on failure with exponential backoff.
| Option | Type | Default | Description |
|---|---|---|---|
maxAttempts | number | 3 | Maximum number of retry attempts (excluding first attempt) |
factor | number | 2 | Exponential backoff multiplier |
minTimeout | number | 1000 | Initial retry delay in milliseconds |
maxTimeout | number | 60000 | Maximum retry delay in milliseconds |
randomize | boolean | true | Add random jitter to retry delays |
Retry Defaults Configuration
Tasks also support a retries.default option in task configuration used by internal error retry mechanics:
Sources: packages/core/CHANGELOG.md481-485
The retry system (implementation in packages/core/package.json42 v3/utils/retries) distinguishes between error types:
Error Categories:
| Error Type | Behavior | Example |
|---|---|---|
| Retryable | Automatic retry with backoff | Network errors, 500-level HTTP, 429 rate limits |
| Non-retryable | Immediate failure | 400-level TriggerApiError, validation errors |
| System Failures | Special handling | Segfaults, FFmpeg OOM, Worker OOM |
Special Error Detection:
TriggerApiError Handling (v4.0.0-beta.7):
4xx errors from TriggerApiError are treated as non-retryable to prevent wasted retry attempts on client errors.
Sources: packages/cli-v3/CHANGELOG.md226 packages/trigger-sdk/CHANGELOG.md721-722 packages/trigger-sdk/CHANGELOG.md729-730 packages/core/CHANGELOG.md504-508
Queues allow you to control concurrency and organize tasks into execution groups.
| Property | Type | Description |
|---|---|---|
name | string | Queue identifier (optional, defaults to task ID) |
concurrencyLimit | number | null | Maximum concurrent runs in this queue |
Concurrency Consumption (v4.0.0-v4-beta.24):
Tasks consume concurrency tokens at two levels:
Burst Factor (v4.0.0-v4-beta.24): Environment concurrency limits include a "Burst Factor" (default 2.0x). If your environment limit is 100 and burst factor is 2.0x, you can execute up to 200 runs concurrently, but any single task/queue is still limited to 100.
Run Status Helpers (v4.0.0-v4-beta.24):
The SDK provides boolean helpers to check run states:
Concurrency Release Behavior (v4.0.0-v4-beta.24):
Sources: packages/trigger-sdk/CHANGELOG.md456-497 packages/trigger-sdk/CHANGELOG.md263-267
Machine presets control the compute resources allocated to task execution.
| Preset | vCPU | Memory | Use Case |
|---|---|---|---|
micro | 0.25 | 0.5 GB | Lightweight tasks |
small-1x | 0.5 | 1 GB | Standard tasks (default) |
small-2x | 1.0 | 2 GB | Moderate workloads |
medium-1x | 1.0 | 2 GB | Medium tasks |
medium-2x | 2.0 | 4 GB | Heavy tasks |
large-1x | 2.0 | 4 GB | Large tasks |
large-2x | 4.0 | 8 GB | Very large tasks |
Machine presets can also be overridden at trigger time:
Sources: packages/trigger-sdk/CHANGELOG.md726-754 packages/trigger-sdk/CHANGELOG.md608
The maxDuration option sets a time limit for task execution. If a task exceeds this duration, it will be forcibly stopped.
number (seconds)TIMED_OUT status if exceededtrigger.config.tsSources: packages/trigger-sdk/CHANGELOG.md178 packages/core/CHANGELOG.md506-507 packages/cli-v3/CHANGELOG.md297
Scheduled tasks execute on a recurring schedule defined by a cron expression. They are managed by the internal ScheduleEngine system in internal-packages/schedule-engine/.
Export Location: packages/trigger-sdk/package.json24-27 exports schedules object from ./src/v3/index.ts
Sources: packages/trigger-sdk/package.json24-27 Diagram inferred from schedule engine architecture
Sources: packages/trigger-sdk/src/v3/index.ts
┌───────────── minute (0 - 59)
│ ┌───────────── hour (0 - 23)
│ │ ┌───────────── day of month (1 - 31)
│ │ │ ┌───────────── month (1 - 12)
│ │ │ │ ┌───────────── day of week (0 - 6) (Sunday to Saturday)
│ │ │ │ │
│ │ │ │ │
* * * * *
Common Patterns:
| Pattern | Description |
|---|---|
0 * * * * | Every hour |
*/15 * * * * | Every 15 minutes |
0 9 * * * | Daily at 9:00 AM |
0 9 * * 1 | Every Monday at 9:00 AM |
0 0 1 * * | First day of every month at midnight |
0 0 * * 0 | Every Sunday at midnight |
Cron Expression Utilities:
cronstrue package (v2.21.0) converts cron expressions to human-readable descriptions"cronstrue": "^2.21.0"Scheduled tasks support all standard task configuration options:
Database Schema: Scheduled tasks are stored in PostgreSQL:
TaskSchedule table: Stores schedule metadata and cron expressionsBackgroundWorkerTask table: References the task definitionTaskRun table: Each schedule execution creates a new run recordSchedule Engine Behavior:
TaskSchedule recordsTaskRun with status DELAYEDRunEngine.DequeueSystemSources: packages/trigger-sdk/package.json57 Database schema inference from patterns
Tasks can be converted to AI SDK tools, allowing language models to execute background tasks as function calls.
Location: packages/trigger-sdk/src/v3/ai.ts
The ai.tool() function wraps a Trigger.dev task for use with the Vercel AI SDK as a tool.
Export Location: packages/trigger-sdk/package.json24-28 exports ai object from ./src/v3/ai.ts
Schema Extraction:
Sources: packages/trigger-sdk/package.json38-40 (ai export), packages/trigger-sdk/CHANGELOG.md320-321
The recommended approach uses schemaTask() for automatic schema conversion:
Sources: packages/trigger-sdk/CHANGELOG.md127 packages/trigger-sdk/src/v3/ai.ts
For tasks defined with jsonSchema, the schema is used directly:
Sources: packages/trigger-sdk/CHANGELOG.md389 packages/trigger-sdk/CHANGELOG.md215
Version Support (v4.0.0-v4-beta.28):
Trigger.dev supports AI SDK 5.0. The ai.tool() function accepts:
schemaTask() with Zod schemastask() with jsonSchema parameterPeer Dependencies:
"ai": "^4.2.0 || ^5.0.0" as optional peer dependencyai.tool() functionalitySources: packages/trigger-sdk/CHANGELOG.md320-321 packages/trigger-sdk/package.json81-83
The toolTask() function has been deprecated. Use the pattern above instead:
Sources: packages/trigger-sdk/CHANGELOG.md234 packages/trigger-sdk/CHANGELOG.md657
Tasks move through multiple phases from developer code to production execution.
Sources: packages/cli-v3/package.json33-34 (CLI binary), packages/core/package.json52 (worker exports)
Task Discovery (Build Phase):
trigger.config.ts (default: ./trigger)task() and schemaTask() callsTask Indexing (Deploy Phase):
trigger deploy command sends task metadata to platform APIBackgroundWorkerTask records in PostgreSQLTaskSchedule recordsTask Execution (Runtime):
TaskRun record created when task is triggeredRunEngine (in packages/core/package.json52) dequeues runTaskExecutor class loads task module and invokes run() functiononStartAttempt, onSuccess, etc.) executed at appropriate pointsTask Configuration Access:
During execution, the TaskExecutor has access to:
BackgroundWorkerTask tableRunAttemptSystemSources: packages/core/package.json52-53 CLI deploy command architecture
The returned task object provides methods for triggering executions:
See Task Triggering and Scheduling for detailed documentation of these methods.
Sources: packages/trigger-sdk/src/v3/index.ts
Sources: packages/trigger-sdk/CHANGELOG.md26-57 packages/trigger-sdk/CHANGELOG.md401-414
TypeScript automatically infers types based on the task definition:
Sources: Based on TypeScript inference patterns common in the SDK
The Task Definition API provides a declarative way to define background jobs with:
id and run function requiredTasks defined with this API are automatically registered, versioned, and made available for triggering from anywhere in your application (see Task Triggering and Scheduling).
Sources: packages/trigger-sdk/package.json1-131 packages/trigger-sdk/CHANGELOG.md1-949
Refresh this wiki