Basic Task Definition
Define a task using thehy.task()
method:
Tasks can accept either zero arguments or one JSON-serializable argument. The return value must also be JSON-serializable or void.
Task Configuration
Configure task behavior with the config object:Configuration Options
- queue: Route tasks to specific worker pools (default: “default”)
- maxRetries: Number of retry attempts on failure (0-10, default: 3)
- timeoutSeconds: Maximum execution time before timeout
- priority: Task priority from 1-10 (default: 3)
- cron: Cron expression for scheduled tasks
- idempotencyKey: Unique key to prevent duplicate task executions
Sending Tasks
Queue tasks for asynchronous execution:Task Context
Access metadata about the current task execution:Context Properties
- taskId: Unique identifier for the task
- durableId: Persistent identifier for durable task storage
- rootId: ID of the root task in the task tree
- parentId: ID of the parent task (null if root)
- workflowRunId: ID of the workflow run (if part of workflow)
- taskName: Name of the task being executed
- queue: Queue name where task is processed
- priority: Task priority level
- attemptNumber: Current attempt number (0-based)
- maxRetries: Maximum retry attempts configured
- timeoutSeconds: Timeout configuration
- executorId: ID of the executor processing this task
Error Handling
Tasks can throw errors to trigger retries:Retry Behavior
- Throwing any exception triggers a retry (if retries remain)
- Return a value to complete the task (even with errors)
- Retries use exponential backoff by default
Input Validation
Use Zod schemas for type-safe input validation:Task Results
Thesend()
method returns a task ID immediately:
Best Practices
-
Use Type-Safe Interfaces
-
Set Appropriate Timeouts
-
Design for Idempotency
-
Handle Errors Gracefully