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

Menu

Task Definition API

Relevant source files

Purpose and Scope

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.


Task Definition Functions

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.

The task() Function

The 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 run
  • batchTrigger(items, options) - Enqueues multiple runs
  • triggerAndWait(payload, options) - Enqueues and waits for completion
  • batchTriggerAndWait(items, options) - Enqueues multiple and waits for all

Sources: packages/trigger-sdk/src/v3/shared.ts138-161 packages/core/src/v3/types/tasks.ts100-180

The schemaTask() Function

The 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

The toolTask() Function

The 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


Task Definition Flow

Sources: packages/trigger-sdk/src/v3/shared.ts138-210 packages/core/src/v3/resource-catalog-api.ts1-50


Task Options Structure

Core Task Options

The TaskOptions interface defines the configuration for a task:

OptionTypeRequiredDescription
idstringYesUnique identifier for the task
runfunctionYesThe main execution function
retryRetryOptionsNoRetry configuration
queueQueueNoQueue assignment
machineMachinePresetNoCompute resource preset
maxDurationnumberNoMaximum execution time in seconds
descriptionstringNoHuman-readable description
jsonSchemaJSONSchemaNoJSON schema for the payload

Sources: packages/core/src/v3/types/tasks.ts100-180

Task Identifier

The id field must be a unique string that identifies the task within your project. It is used for:

  • Routing trigger requests to the correct task
  • Referencing tasks in the dashboard
  • Parent-child task relationships

Sources: packages/trigger-sdk/src/v3/shared.ts163

The run Function

The 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 run
  • init: TInitOutput - Output from init hooks
  • signal: AbortSignal - Cancellation signal

Sources: packages/core/src/v3/types/tasks.ts41-47 packages/core/src/v3/schemas/common.ts300-350

Retry Configuration

The retry option configures automatic retry behavior:

Retry Behavior:

  1. Failed tasks are retried up to maxAttempts times
  2. Delay between retries follows exponential backoff: minTimeout * (factor ^ attemptNumber)
  3. Delay is capped at maxTimeoutInMs
  4. Optional randomization prevents thundering herd

Sources: packages/core/src/v3/schemas/common.ts157-174 packages/core/src/v3/utils/retries.ts1-100

Queue Assignment

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

Machine Presets

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 RAM

Sources: packages/core/src/v3/schemas/common.ts230-270


Task Metadata Registration

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


TaskMetadataWithFunctions Structure

Internally, tasks are represented as TaskMetadataWithFunctions objects that contain both metadata and executable functions:

Key Fields:

  • id - The task identifier
  • fns - Object containing all executable functions (run, hooks, error handlers)
  • retry - Retry configuration
  • queue - Queue metadata
  • machine - Machine preset

Sources: packages/core/src/v3/types/index.ts50-100


Schema Validation Flow

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


Task Registration During Build

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


Task Object API Reference

The Task object returned by task(), schemaTask(), and toolTask() provides the following methods:

trigger()

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

batchTrigger()

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

triggerAndWait()

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

batchTriggerAndWait()

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


Lifecycle Hook Integration

Tasks can include lifecycle hooks directly in their definition or register them globally. The following hooks are supported:

HookPhasePurpose
initBefore first attemptInitialize resources
onStartBefore first attemptFirst-time setup (deprecated)
onStartAttemptBefore each attemptPer-attempt setup
middlewareAround run functionWrap execution
onSuccessAfter successHandle success
onFailureAfter failureHandle failure
onCompleteAfter finishCleanup (success or failure)
cleanupAfter all hooksFinal cleanup
onWaitWhen suspendingHandle suspension
onResumeWhen resumingHandle resumption
onCancelWhen canceledHandle cancellation
handleErrorOn errorCustom error handling

Registration in Task Definition:

Sources: packages/core/src/v3/types/tasks.ts100-180 packages/core/src/v3/lifecycleHooks/types.ts1-200


Task Execution Context

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


Error Handling and Task Errors

Task execution errors are classified by error codes defined in TaskRunErrorCodes:

Error CodeDescriptionRetryable
TASK_INPUT_ERRORPayload validation failedNo
TASK_OUTPUT_ERROROutput serialization failedNo
TASK_EXECUTION_ERRORUser code threw errorYes
TASK_MIDDLEWARE_ERRORMiddleware threw errorNo
INTERNAL_ERRORSystem errorYes
HANDLE_ERROR_ERRORError handler threw errorNo

Error Flow:

  1. Error occurs in run() function
  2. handleError hook (if defined) processes error
  3. TaskExecutor determines if retry should occur
  4. onFailure hook called if not retrying
  5. onComplete hook called with error result

Sources: packages/core/src/v3/schemas/common.ts450-500 packages/core/src/v3/workers/taskExecutor.ts199-247


Summary

The Task Definition API provides three functions for defining tasks:

  • task() for standard tasks with TypeScript types
  • schemaTask() for tasks with runtime schema validation
  • toolTask() for AI SDK tool integration

Tasks 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