To add tasks to a queue, you must first create a Factory for your chosen backend (e.g., redisq.NewFactory()), register a Queue using RegisterQueue, and define tasks using RegisterTask. Once the queue is initialized, use the Add method on the queue instance to enqueue tasks. Tasks can be configured with arguments using the WithArgs method.
import (
"github.com/vmihailenco/taskq/v3"
"github.com/vmihailenco/taskq/v3/redisq"
)
// Create a queue factory.
var QueueFactory = redisq.NewFactory()
// Create a queue.
var MainQueue = QueueFactory.RegisterQueue(&taskq.QueueOptions{
Name: "api-worker",
Redis: Redis, // go-redis client
})
// Register a task.
var CountTask = taskq.RegisterTask(&taskq.TaskOptions{
Name: "counter",
Handler: func() error {
IncrLocalCounter()
return nil
},
})
ctx := context.Background()
// And start producing.
for {
// Call the task without any args.
err := MainQueue.Add(CountTask.WithArgs(ctx))
if err != nil {
panic(err)
}
time.Sleep(time.Second)
}