v1.1.3

Getting Started

Last updated


This page covers installing go-queue, starting a worker pool, enqueueing a first task, and shutting the queue down within a deadline.

Prerequisites


ItemRequirement
Go1.23 or higher (go.mod declares go 1.23)
External dependenciesNone; standard library only

Installation


  1. go get github.com/pardnchiu/go-queue

  1. import "github.com/pardnchiu/go-queue/core"

The public API lives in the core sub-package. This path ships in the first release after v1.1.3; until that tag exists, use go get github.com/pardnchiu/go-queue@develop.

Your First Queue


  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "time"
  7. "github.com/pardnchiu/go-queue/core"
  8. )
  9. func main() {
  10. q := core.New(&core.Config{Workers: 4})
  11. ctx := context.Background()
  12. if err := q.Start(ctx); err != nil {
  13. log.Fatal(err)
  14. }
  15. for i := range 3 {
  16. id, err := q.Enqueue(ctx, "", func(ctx context.Context) error {
  17. fmt.Println("task", i, "running")
  18. return nil
  19. })
  20. if err != nil {
  21. log.Printf("enqueue: %v", err)
  22. continue
  23. }
  24. fmt.Println("enqueued", id)
  25. }
  26. // Drain the queue, waiting at most 10 seconds
  27. shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  28. defer cancel()
  29. if err := q.Shutdown(shutdownCtx); err != nil {
  30. log.Printf("shutdown: %v", err)
  31. }
  32. }

Each task emits one task.completed slog record with the task ID, preset name, and elapsed time.

Three Lifecycle Calls


StepCallKey Point
Createcore.New(cfg)cfg may be nil; zero-value fields take defaults
Startq.Start(ctx)Launches Workers goroutines; cancelling ctx cancels every running task's ctx
Shut downq.Shutdown(ctx)Rejects new tasks, then waits for workers to drain the heap; returns an error when ctx expires

Enqueue also works before Start: tasks wait in the heap and run by priority once Start is called.

Next Steps


中文