2
0
mirror of https://github.com/hibiken/asynq.git synced 2024-12-27 00:02:19 +08:00
asynq/client.go

93 lines
2.0 KiB
Go
Raw Normal View History

package asynq
import (
"time"
2019-12-22 23:15:45 +08:00
"github.com/hibiken/asynq/internal/base"
2019-12-04 13:01:26 +08:00
"github.com/hibiken/asynq/internal/rdb"
"github.com/rs/xid"
)
2019-12-07 14:00:09 +08:00
// A Client is responsible for scheduling tasks.
//
2019-12-09 22:52:43 +08:00
// A Client is used to register tasks that should be processed
2019-12-07 14:00:09 +08:00
// immediately or some time in the future.
//
// Clients are safe for concurrent use by multiple goroutines.
type Client struct {
2019-12-04 13:01:26 +08:00
rdb *rdb.RDB
}
2019-12-07 14:00:09 +08:00
// NewClient and returns a new Client given a redis configuration.
2019-12-09 22:22:08 +08:00
func NewClient(cfg *RedisConfig) *Client {
r := rdb.NewRDB(newRedisClient(cfg))
2019-12-04 13:01:26 +08:00
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
)
2019-12-07 14:00:09 +08:00
// Process registers a task to be processed at the specified time.
//
2019-12-09 22:52:43 +08:00
// Process returns nil if the task is registered successfully,
2019-12-07 14:00:09 +08:00
// otherwise returns non-nil error.
2019-12-22 02:02:03 +08:00
//
// opts specifies the behavior of task processing. If there are conflicting
// Option the last one overrides the ones before.
func (c *Client) Process(task *Task, processAt time.Time, opts ...Option) error {
opt := composeOptions(opts...)
2019-12-22 23:15:45 +08:00
msg := &base.TaskMessage{
ID: xid.New(),
Type: task.Type,
Payload: task.Payload,
Queue: "default",
Retry: opt.retry,
}
2019-11-27 23:16:16 +08:00
return c.enqueue(msg, processAt)
}
2019-12-22 23:15:45 +08:00
func (c *Client) enqueue(msg *base.TaskMessage, processAt time.Time) error {
2019-11-27 23:16:16 +08:00
if time.Now().After(processAt) {
2019-12-04 13:01:26 +08:00
return c.rdb.Enqueue(msg)
}
return c.rdb.Schedule(msg, processAt)
}