WHAT YOU'LL LEARN
  • How to create your own background tasks?
  • How to implement the TaskDefinition interface?
  • How to handle task lifecycle hooks?
  • How to validate task input parameters?
  • How to control task execution and handle errors?

Overview
anchor

Tasks in the system allow you to execute long-running operations asynchronously without blocking the main request-response cycle. By implementing the TaskDefinition.Interface and registering it with TaskDefinition.createImplementation(), you can create custom background tasks that handle complex operations like batch processing, data migrations, or bulk actions.

A task definition includes:

  • Task metadata - Unique ID, title, description, and configuration options (max iterations, logging, visibility)
  • Main execution method - The run() method that processes the task with input/output type safety
  • Runtime control - Check execution status with controller.runtime.isAborted() and controller.runtime.isCloseToTimeout()
  • Lifecycle hooks - Methods triggered at different stages: onBeforeTrigger, onDone, onError, onAbort, and onMaxIterations
  • Input validation - Schema-based validation using the createInputValidation() method
  • Dependency injection - Access to use cases and services through createImplementation()

The TaskDefinition namespace provides all the necessary types for implementing your task, while TaskDefinition.createImplementation() handles the registration with dependency injection. The task controller provides runtime control methods to check if execution should be aborted or is close to timeout, and response methods to return different task states:

  • controller.response.done() - Task completed successfully
  • controller.response.continue() - Task needs to continue in the next iteration (useful for long-running operations)
  • controller.response.error() - Task failed with an error
  • controller.response.aborted() - Task was manually aborted

This pattern keeps background tasks modular, testable, and easy to monitor.

Usage Example
anchor