mirror of
https://github.com/hibiken/asynq.git
synced 2025-09-19 05:17:30 +08:00
Allow user to define a max retry count for a task
This commit is contained in:
48
client.go
48
client.go
@@ -3,8 +3,8 @@ package asynq
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/rs/xid"
|
||||
"github.com/hibiken/asynq/internal/rdb"
|
||||
"github.com/rs/xid"
|
||||
)
|
||||
|
||||
// A Client is responsible for scheduling tasks.
|
||||
@@ -23,17 +23,59 @@ func NewClient(cfg *RedisConfig) *Client {
|
||||
return &Client{r}
|
||||
}
|
||||
|
||||
// Option configures the behavior of task processing.
|
||||
type Option interface{}
|
||||
|
||||
// max number of times a task will be retried.
|
||||
type retryOption int
|
||||
|
||||
// MaxRetry returns an option to specify the max number of times
|
||||
// a task will be retried.
|
||||
//
|
||||
// Negative retry count is treated as zero retry.
|
||||
func MaxRetry(n int) Option {
|
||||
if n < 0 {
|
||||
n = 0
|
||||
}
|
||||
return retryOption(n)
|
||||
}
|
||||
|
||||
type option struct {
|
||||
retry int
|
||||
}
|
||||
|
||||
func composeOptions(opts ...Option) option {
|
||||
res := option{
|
||||
retry: defaultMaxRetry,
|
||||
}
|
||||
for _, opt := range opts {
|
||||
switch opt := opt.(type) {
|
||||
case retryOption:
|
||||
res.retry = int(opt)
|
||||
default:
|
||||
// ignore unexpected option
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
const (
|
||||
// Max retry count by default
|
||||
defaultMaxRetry = 25
|
||||
)
|
||||
|
||||
// Process registers a task to be processed at the specified time.
|
||||
//
|
||||
// Process returns nil if the task is registered successfully,
|
||||
// otherwise returns non-nil error.
|
||||
func (c *Client) Process(task *Task, processAt time.Time) error {
|
||||
func (c *Client) Process(task *Task, processAt time.Time, opts ...Option) error {
|
||||
opt := composeOptions(opts...)
|
||||
msg := &rdb.TaskMessage{
|
||||
ID: xid.New(),
|
||||
Type: task.Type,
|
||||
Payload: task.Payload,
|
||||
Queue: "default",
|
||||
Retry: defaultMaxRetry,
|
||||
Retry: opt.retry,
|
||||
}
|
||||
return c.enqueue(msg, processAt)
|
||||
}
|
||||
|
Reference in New Issue
Block a user