The Tasker pattern is a structured approach for managing non-critical background tasks (e.g., sending emails, generating reports, or maintenance) to improve application responsiveness. It provides a mechanism for task scheduling, execution, automatic retries, and cancellation.
Core Concepts
- Offloading: Instead of executing a task immediately on the main thread, you schedule it via a Tasker. This moves the execution to a separate queue.
- Retry Mechanism: If a task fails, the system automatically increments the
attempts count and retries it on the next processing cycle. By default, tasks are attempted up to 3 times, though this can be overridden during task creation. - Task Lifecycle:
- Success: The task is marked with
suceededAt: new Date(). - Failure: The
attempts property increases. If attempts reaches maxAttemps, the task is marked as failed and is no longer retried.
- Implementation Types:
InternalTasker: A built-in implementation that requires no third-party dependencies and relies on a configured cron job.- Third-party Taskers: The pattern is modular, allowing replacement with services like
TriggerDevTasker or AwsSqsTasker.
Task Definition
A task is defined as a function that receives a string payload:
type TaskHandler = (payload: string) => Promise<void>;
type TaskHandler = (payload: string) => Promise<void>;