queue package provides a flexible job processing system with typed job handlers, worker pools, and graceful shutdown.
Processor Type
TheProcessor[T] type manages a pool of workers to process jobs from a queue.
Constructor
*Processor[T]
Creates a new Processor with the specified configuration.Parameters:
handler(Handler[T]): The handler to process jobsqueue(Provider[T]): The queue provider implementationworkersAmount(int): Number of concurrent workersshutdownTimeout(time.Duration): Time to wait for in-progress jobs during shutdown
Processor Methods
Enqueue
error
Adds a job to the queue for processing.
Run
error
Starts the queue processor and blocks until all workers complete.Lifecycle:
- Opens the queue provider
- Starts the configured number of workers
- Workers process jobs until context is canceled
- Attempts to drain remaining jobs within shutdown timeout
- Closes the queue provider
Handler Interface
The Handler interface defines how jobs are processed.func(ctx context.Context, job T)
Processes a single job. This method is called by workers for each job in the queue.
HandlerFunc
A function type that implements the Handler interface.Provider Interface
The Provider interface defines queue implementations.func(ctx context.Context) error
Initializes the queue provider (e.g., connects to Redis, opens channels).
func(ctx context.Context) error
Closes the queue provider and cleans up resources.
func(ctx context.Context, job T) error
Adds a job to the queue.
func(ctx context.Context) (chan T, error)
Returns a channel that workers can receive jobs from.
Built-in Queue Provider
ChanQueue
Platforma provides a channel-based queue implementation for simple use cases:Example Usage
Basic Job Processing
Struct Handler
Integration with Application
Graceful Shutdown
The processor handles graceful shutdown automatically:- Context Cancellation: Workers stop accepting new jobs
- Drain Period: Workers attempt to finish in-progress jobs within the shutdown timeout
- Cleanup: Queue provider is closed
Context Keys
The processor automatically adds aWorkerIDKey to the context for each worker: