Tasks
Reference
Tasks Reference
- How to create your own background tasks?
- How to implement the
TaskDefinitioninterface? - How to handle task lifecycle hooks?
- How to validate task input parameters?
- How to control task execution and handle errors?
Overview
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()andcontroller.runtime.isCloseToTimeout() - Lifecycle hooks - Methods triggered at different stages:
onBeforeTrigger,onDone,onError,onAbort, andonMaxIterations - 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 successfullycontroller.response.continue()- Task needs to continue in the next iteration (useful for long-running operations)controller.response.error()- Task failed with an errorcontroller.response.aborted()- Task was manually aborted
This pattern keeps background tasks modular, testable, and easy to monitor.
Usage Example