Thanks to visit codestin.com
Credit goes to deepwiki.com

Menu

Task Definition API

Relevant source files

Overview

This page documents the API for defining tasks in Trigger.dev using the @trigger.dev/sdk/v3 package. Tasks are the fundamental unit of work in Trigger.dev—async functions that can be triggered programmatically, scheduled via cron, and monitored through the platform.

API Coverage:

Core Type Definitions:

Related Documentation:

  • For triggering tasks programmatically: See page 3.2 (Task Triggering and Scheduling)
  • For lifecycle hooks (onSuccess, onFailure, onCancel): See page 3.4 (Lifecycle Hooks)
  • For runtime utilities (wait, metadata, etc.): See SDK documentation

Sources: packages/trigger-sdk/src/v3/shared.ts132-618 packages/trigger-sdk/src/v3/tasks.ts1-71 packages/core/src/v3/types/tasks.ts1-300

Core Task Definition

Tasks are defined using the task() function exported from @trigger.dev/sdk/v3. The task() function is a thin wrapper around createTask() packages/trigger-sdk/src/v3/shared.ts132-160 which constructs a Task<TIdentifier, TInput, TOutput> object.

Basic Structure

Return Value: The task() function returns a Task object packages/core/src/v3/types/tasks.ts with the following methods:

The exported task is automatically discovered during deployment (via the trigger deploy command) and registered with the platform through the task indexing process.

Sources: packages/trigger-sdk/src/v3/shared.ts132-216 packages/trigger-sdk/src/v3/tasks.ts15-24 packages/core/src/v3/types/tasks.ts95-150

Task Configuration Object Structure

Diagram: TaskOptions Type Structure

Sources: packages/core/src/v3/types/tasks.ts17-94 packages/core/src/v3/lifecycleHooks/types.ts1-100 packages/core/src/v3/schemas/index.ts

Required Properties

id

The id property is a unique string identifier for the task within your project. Task IDs must be URL-friendly and unique across all tasks in an environment.

PropertyTypeRequiredDescription
idstringYesUnique task identifier. URL-safe characters only.

Task IDs are used when triggering tasks programmatically and appear in logs, traces, and the dashboard. Changing a task's ID creates a new task from the platform's perspective.

Sources: packages/trigger-sdk/CHANGELOG.md203-206 docs/guides/examples/fal-ai-image-to-cartoon.mdx31-53

run

The run property is an async function containing the task's execution logic. It receives the task payload and a context object.

PropertyTypeRequiredDescription
runasync (payload, { ctx }) => Promise<TOutput>YesTask execution function

The function signature is:

  • payload: The data passed when the task is triggered. Type inferred from schema or generic type parameter.
  • ctx: Context object containing run metadata, environment info, and utility methods.
  • Returns: A promise resolving to the task output. Type inferred from schema or generic type parameter.

Sources: packages/trigger-sdk/CHANGELOG.md125-149 docs/guides/examples/scrape-hacker-news.mdx80-276

Schema Definition

Tasks support type-safe payload and output definitions using Zod schemas. Schemas provide both compile-time TypeScript types and runtime validation.

Using task() with TypeScript Generics

This approach provides compile-time type checking but no runtime validation.

Sources: packages/trigger-sdk/CHANGELOG.md36-46 docs/guides/examples/fal-ai-image-to-cartoon.mdx30-80

Using schemaTask() for Runtime Validation

The schemaTask() function is implemented via createSchemaTask() packages/trigger-sdk/src/v3/shared.ts284-445 and adds runtime schema validation using Zod schemas. The function uses getSchemaParseFn() packages/trigger-sdk/src/v3/shared.ts295-313 to create a validation function from the Zod schema.

schemaTask() Configuration:

PropertyTypeRequiredDescription
schemaZodSchemaYesZod schema for validating task payload
outputZodSchemaNoZod schema for validating return value

Validation Behavior:

Sources: packages/trigger-sdk/src/v3/shared.ts284-445 packages/core/src/v3/workers/taskExecutor.ts133-135 packages/core/src/v3/types/tasks.ts27-40

Schema Validation Flow

Diagram: Task Execution with Schema Validation

Sources: packages/core/src/v3/workers/taskExecutor.ts92-359 packages/trigger-sdk/src/v3/shared.ts284-313

Retry Configuration

Tasks automatically retry on failure using exponential backoff. Retry behavior is configurable via the retry property.

Retry Options

PropertyTypeDefaultDescription
maxAttemptsnumber3Maximum number of execution attempts
minTimeoutnumber (seconds)1Initial retry delay
maxTimeoutnumber (seconds)60Maximum retry delay
factornumber2Exponential backoff multiplier
randomizebooleantrueAdd jitter to retry delays

Configuration Example

Retry Behavior

The retry mechanism follows this pattern:

  1. Attempt 1: Initial execution
  2. Attempt 2: Retry after minTimeout (e.g., 2s)
  3. Attempt 3: Retry after minTimeout * factor (e.g., 4s)
  4. Attempt 4: Retry after previous delay * factor (e.g., 8s)
  5. Continues until maxAttempts reached or maxTimeout limit hit

Randomization (jitter) helps prevent thundering herd problems when many tasks fail simultaneously.

Sources: packages/trigger-sdk/CHANGELOG.md364-389 packages/core/CHANGELOG.md457-461

Retry State Transitions

Sources: packages/trigger-sdk/CHANGELOG.md154-195 packages/core/CHANGELOG.md356-389

Machine Presets

The machine property specifies the compute resources allocated to task execution. Trigger.dev provides several preset configurations optimized for different workload types.

Available Presets

PresetvCPUMemoryUse Case
micro0.50.5 GBLightweight tasks, API calls
small-1x11 GBDefault, general purpose
small-2x22 GBCPU-intensive operations
medium-1x24 GBMemory-intensive operations
medium-2x48 GBLarge data processing
large-1x416 GBVery large datasets
large-2x832 GBMaximum resources

Configuration Example

Runtime Machine Override

Machine presets can be overridden when triggering a task:

Sources: packages/trigger-sdk/CHANGELOG.md644-672 packages/core/CHANGELOG.md240-269

Queue Configuration

The queue property controls task concurrency and execution behavior. Queues allow grouping tasks and managing how many instances can run simultaneously.

Queue Options

PropertyTypeDescription
namestringQueue identifier (optional, defaults to task ID)
concurrencyLimitnumberMax concurrent runs (per environment)

Configuration Example

Queue Behavior

  • Tasks in the same queue share concurrency limits
  • When the limit is reached, new tasks wait in queue (QUEUED state)
  • Tasks are dequeued in FIFO order (unless priority is specified)
  • Each environment has independent queue limits

Concurrency Control Flow

Sources: packages/trigger-sdk/CHANGELOG.md154-160 docs/manual-setup.mdx1-24

Maximum Duration

The maxDuration property sets a timeout for task execution, specified in seconds.

PropertyTypeDefaultDescription
maxDurationnumberNo limitMaximum execution time in seconds

Configuration Example

When a task exceeds maxDuration:

  1. The task run transitions to TIMED_OUT state
  2. The execution process receives a termination signal
  3. The task is not automatically retried (timeout is considered final)

Sources: packages/trigger-sdk/CHANGELOG.md169 packages/core/CHANGELOG.md482

Context Parameter

The run function receives a RunFnParams<TInit> object packages/core/src/v3/types/tasks.ts as its second parameter, which includes the ctx: TaskRunContext providing access to run metadata, environment information, and platform utilities.

TaskRunContext Type Structure

The TaskRunContext interface is defined in packages/core/src/v3/schemas/index.ts and passed to the task executor in packages/core/src/v3/workers/taskExecutor.ts92-96:

Usage Example

Sources: packages/core/src/v3/schemas/index.ts packages/core/src/v3/types/tasks.ts95-110 packages/core/src/v3/workers/taskExecutor.ts92-96

Context Hierarchy Diagram

Diagram: TaskRunContext Structure and Code Mappings

Sources: packages/core/src/v3/schemas/index.ts packages/core/src/v3/workers/taskExecutor.ts92-96

Initialization Hook

The init property is typed as OnInitHookFunction<TPayload, TInitOutput> packages/core/src/v3/lifecycleHooks/types.ts13-15 and allows running setup code once per task execution environment (process or container). The init hook is executed by TaskExecutor#callInitFunctions() packages/core/src/v3/workers/taskExecutor.ts180

The init hook can return TaskInitOutput, which is defined as Record<string, any> | void | undefined packages/core/src/v3/lifecycleHooks/types.ts4

Configuration Example

The init hook:

Sources: packages/core/src/v3/lifecycleHooks/types.ts1-17 packages/core/src/v3/workers/taskExecutor.ts180 packages/core/src/v3/lifecycleHooks/manager.ts20-22

Scheduled Tasks

The schedules.task() function defines tasks that run automatically on a cron schedule. These tasks do not require manual triggering and execute according to their configured schedule.

Basic Scheduled Task

Scheduled Task Configuration

PropertyTypeRequiredDescription
idstringYesUnique task identifier
cronstringYesCron expression (5-field or 6-field format)
runfunctionYesExecution function (receives timestamp payload)
timezonestringNoIANA timezone (default: "UTC")

Cron Expression Format:

  • 5-field: "* * * * *" (minute, hour, day, month, day-of-week)
  • 6-field: "* * * * * *" (second, minute, hour, day, month, day-of-week)

Scheduled Task with Schema

Payload Structure: Scheduled tasks automatically receive a payload with:

  • timestamp: Date - When the schedule was triggered
  • timezone: string - The timezone used for scheduling
  • lastTimestamp: Date (optional) - The previous execution timestamp

Configuration Options: Scheduled tasks support the same configuration options as regular tasks:

  • retry - Retry configuration
  • machine - Machine preset
  • queue - Queue configuration
  • maxDuration - Timeout in seconds
  • init - Initialization hook

Sources: packages/trigger-sdk/CHANGELOG.md1-50 packages/core/CHANGELOG.md1-100

Complete Task Definition Example

This example demonstrates a fully-configured task using most available options:

Sources: packages/trigger-sdk/CHANGELOG.md1-206

Task Definition to Runtime Flow

Sources: packages/trigger-sdk/CHANGELOG.md1-206 packages/core/CHANGELOG.md1-632 packages/cli-v3/CHANGELOG.md1-700