2019-11-20 13:19:46 +08:00
|
|
|
package asynq
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
2019-11-22 22:16:43 +08:00
|
|
|
"github.com/google/uuid"
|
2019-12-04 13:01:26 +08:00
|
|
|
"github.com/hibiken/asynq/internal/rdb"
|
2019-11-20 13:19:46 +08:00
|
|
|
)
|
|
|
|
|
2019-12-07 14:00:09 +08:00
|
|
|
// A Client is responsible for scheduling tasks.
|
|
|
|
//
|
|
|
|
// A Client is used to register task that should be processed
|
|
|
|
// immediately or some time in the future.
|
|
|
|
//
|
|
|
|
// Clients are safe for concurrent use by multiple goroutines.
|
2019-11-20 13:19:46 +08:00
|
|
|
type Client struct {
|
2019-12-04 13:01:26 +08:00
|
|
|
rdb *rdb.RDB
|
2019-11-20 13:19:46 +08:00
|
|
|
}
|
|
|
|
|
2019-12-07 14:00:09 +08:00
|
|
|
// NewClient and returns a new Client given a redis configuration.
|
2019-12-04 11:43:01 +08:00
|
|
|
func NewClient(config *RedisConfig) *Client {
|
2019-12-04 13:01:26 +08:00
|
|
|
r := rdb.NewRDB(newRedisClient(config))
|
|
|
|
return &Client{r}
|
2019-11-20 13:19:46 +08:00
|
|
|
}
|
|
|
|
|
2019-12-07 14:00:09 +08:00
|
|
|
// Process registers a task to be processed at the specified time.
|
|
|
|
//
|
|
|
|
// Process returns nil if the task was registered successfully,
|
|
|
|
// otherwise returns non-nil error.
|
2019-11-27 23:16:16 +08:00
|
|
|
func (c *Client) Process(task *Task, processAt time.Time) error {
|
2019-12-04 13:01:26 +08:00
|
|
|
msg := &rdb.TaskMessage{
|
2019-11-22 22:16:43 +08:00
|
|
|
ID: uuid.New(),
|
2019-11-20 13:19:46 +08:00
|
|
|
Type: task.Type,
|
|
|
|
Payload: task.Payload,
|
|
|
|
Queue: "default",
|
|
|
|
Retry: defaultMaxRetry,
|
|
|
|
}
|
2019-11-27 23:16:16 +08:00
|
|
|
return c.enqueue(msg, processAt)
|
2019-11-20 13:19:46 +08:00
|
|
|
}
|
|
|
|
|
2019-12-04 13:01:26 +08:00
|
|
|
func (c *Client) enqueue(msg *rdb.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)
|
2019-11-20 13:19:46 +08:00
|
|
|
}
|
2019-12-04 22:45:30 +08:00
|
|
|
return c.rdb.Schedule(msg, processAt)
|
2019-11-20 13:19:46 +08:00
|
|
|
}
|