2
0
mirror of https://github.com/hibiken/asynq.git synced 2026-02-04 05:11:21 +00:00
Files
asynq/doc.go

74 lines
2.0 KiB
Go
Raw Permalink Normal View History

2020-01-02 18:13:16 -08:00
// Copyright 2020 Kentaro Hibino. All rights reserved.
// Use of this source code is governed by a MIT license
// that can be found in the LICENSE file.
2019-12-06 06:12:44 -08:00
/*
2020-09-07 10:44:10 -07:00
Package asynq provides a framework for Redis based distrubted task queue.
2019-12-06 06:12:44 -08:00
2020-09-07 10:44:10 -07:00
Asynq uses Redis as a message broker. To connect to redis,
specify the connection using one of RedisConnOpt types.
2025-11-04 19:06:18 +03:00
redisConnOpt = asynq.RedisClientOpt{
Addr: "127.0.0.1:6379",
Password: "xxxxx",
DB: 2,
}
2020-09-07 10:44:10 -07:00
The Client is used to enqueue a task.
2019-12-06 06:12:44 -08:00
2025-11-04 19:06:18 +03:00
client := asynq.NewClient(redisConnOpt)
2025-11-04 19:06:18 +03:00
// Task is created with two parameters: its type and payload.
// Payload data is simply an array of bytes. It can be encoded in JSON, Protocol Buffer, Gob, etc.
b, err := json.Marshal(ExamplePayload{UserID: 42})
if err != nil {
log.Fatal(err)
}
2019-12-06 06:12:44 -08:00
2025-11-04 19:06:18 +03:00
task := asynq.NewTask("example", b)
2021-03-20 13:42:13 -07:00
2025-11-04 19:06:18 +03:00
// Enqueue the task to be processed immediately.
info, err := client.Enqueue(task)
2019-12-06 06:12:44 -08:00
2025-11-04 19:06:18 +03:00
// Schedule the task to be processed after one minute.
info, err = client.Enqueue(t, asynq.ProcessIn(1*time.Minute))
2019-12-06 06:12:44 -08:00
2020-09-07 10:44:10 -07:00
The Server is used to run the task processing workers with a given
2020-01-02 19:47:04 -08:00
handler.
2019-12-06 06:12:44 -08:00
2025-11-04 19:06:18 +03:00
srv := asynq.NewServer(redisConnOpt, asynq.Config{
Concurrency: 10,
})
if err := srv.Run(handler); err != nil {
log.Fatal(err)
}
2019-12-06 06:12:44 -08:00
2020-04-15 07:30:59 -07:00
Handler is an interface type with a method which
2020-01-02 19:47:04 -08:00
takes a task and returns an error. Handler should return nil if
the processing is successful, otherwise return a non-nil error.
If handler panics or returns a non-nil error, the task will be retried in the future.
2019-12-06 06:12:44 -08:00
2020-01-02 19:47:04 -08:00
Example of a type that implements the Handler interface.
2025-11-04 19:06:18 +03:00
type TaskHandler struct {
// ...
}
func (h *TaskHandler) ProcessTask(ctx context.Context, task *asynq.Task) error {
switch task.Type {
case "example":
var data ExamplePayload
if err := json.Unmarshal(task.Payload(), &data); err != nil {
return err
}
// perform task with the data
default:
return fmt.Errorf("unexpected task type %q", task.Type)
}
return nil
}
2019-12-06 06:12:44 -08:00
*/
package asynq