Task Builder
Table of Contents
- Introduction
- Project Structure
- Core Components
- Architecture Overview
- Detailed Component Analysis
- Dependency Analysis
- Performance Considerations
- Troubleshooting Guide
- Conclusion
- Appendix
Introduction
The task builder is a core component of the Sparrow task management system, adopting the Fluent API design pattern to provide a concise and intuitive task configuration and creation interface. The system supports multiple execution modes (immediate, timed, periodic), with comprehensive error handling, retry mechanisms, and timeout control functions.
Project Structure
Task builder related code is mainly distributed in the following files:
The task builder system consists of the following core components:
1. Task Builder (TaskBuilder)
Adopting the Fluent API design pattern, providing chain call interfaces:
- Task ID setting:
WithID() - Type definition:
WithType() - Handler function:
WithHandler() - Callback functions:
WithOnComplete(),WithOnCancel() - Scheduling configuration:
WithSchedule(),WithRecurring() - Execution parameters:
WithTimeout(),WithRetry(),WithPriority()
2. Core Interfaces and Types
Taskinterface: Defines standard task behaviorTaskSchedulerinterface: Defines standard scheduler behaviorTaskInfostructure: Encapsulates task metadataTaskSchedulestructure: Defines task scheduling configuration
3. Scheduler Implementation
- Concurrent Scheduler: Supports parallel execution of multiple tasks
- Sequential Scheduler: Strictly executes tasks in order
- Hybrid Scheduler: Intelligently selects execution mode based on task type
The task builder adopts a layered architecture design with clear separation of responsibilities:
Task Builder Design Pattern Analysis
Fluent API Design
The task builder adopts Fluent API design pattern, providing a smooth chain call experience:
The builder has built-in complete parameter validation logic:
Options Pattern Configuration
The scheduler wrapper adopts the options pattern, providing flexible configuration capabilities:
The hybrid scheduler supports selecting execution mode based on task type:
Concurrent Scheduler
The concurrent scheduler supports parallel execution of multiple tasks with the following features:
- Maximum concurrency limit
- Task memory management
- Timeout control
- Retry mechanism
Sequential Scheduler
The sequential scheduler ensures tasks are executed strictly in order:
- Single task execution mode
- Task queue management
- Memory cleanup mechanism
- Retry strategy
Hybrid Scheduler
A scheduler that intelligently selects execution mode:
- Task type mapping
- Dynamic mode switching
- Unified interface encapsulation
Component Dependencies
Concurrency Control
- Default maximum concurrency: 10 tasks
- Dynamic concurrency slot management
- Condition variable optimization for waiting mechanism
Memory Management
- Task TTL (time to live): Default 5 minutes
- Maximum task count: Default 500
- Automatic cleanup mechanism
Retry Strategy
- Exponential backoff algorithm
- Maximum retry interval: 1 minute
- Context timeout control
Execution Mode Selection
- Immediate tasks: Default concurrent execution
- Timed tasks: Sequential execution mode
- Periodic tasks: Sequential execution mode
- Typed tasks: Selected based on configuration
Troubleshooting Guide
Common Issues and Solutions
Task Build Failure
Issue: Task handler cannot be empty
Cause: Task processing function not set
Solution: Ensure WithHandler() method is called
Time Configuration Error
Issue: Timed task execution time must be greater than current time
Cause: Set a past time point
Solution: Use future time point or use WithRecurring()
Concurrency Configuration Issue
Issue: Maximum concurrent tasks must be greater than 0
Cause: Set non-positive number
Solution: Ensure concurrency is greater than 0
Task Cancellation Exception
Issue: Task does not exist
Cause: Task ID error or task already completed
Solution: Check task ID and task status
- Enable detailed logging
- Use
ListTasks()to check task status - Monitor memory usage
- Verify retry configuration is reasonable
Conclusion
The task builder system provides a concise and intuitive task configuration interface through the Fluent API design pattern. The system supports multiple execution modes with comprehensive error handling and retry mechanisms. Through options pattern configuration, users can flexibly customize scheduler behavior. The system's modular design makes extension and maintenance simple.
Appendix
Usage Example Patterns
Basic Task Creation
taskID := app.Scheduler.RunTask(func(ctx context.Context) error {
// Task logic
return nil
})
Timed Task Configuration
app.Scheduler.RunTaskAt(time.Now().Add(10*time.Minute), func(ctx context.Context) error {
// Delayed execution task
return nil
})
Periodic Task Configuration
app.Scheduler.RunTaskRecurring(5*time.Minute, func(ctx context.Context) error {
// Execute every 5 minutes
return nil
})
Typed Task Configuration
app.Scheduler.RunTypedTask("critical-task", func(ctx context.Context) error {
// Critical task uses sequential execution
return nil
})
Best Practices
- Parameter Validation: Always validate input parameter validity
- Error Handling: Implement appropriate error handling and retry mechanisms
- Resource Management: Reasonably set concurrency and memory limits
- Monitoring and Alerting: Establish task execution monitoring and alerting mechanisms
- Configuration Management: Use configuration files to manage scheduler parameters