diff --git a/instance.go b/instance.go index c82af94..2e50444 100644 --- a/instance.go +++ b/instance.go @@ -14,6 +14,8 @@ type Instance struct { Scheduler *asynq.Scheduler } +var instance Instance + // NewInstance ... func NewInstance(cfg Config) Instance { // Init redis connection @@ -24,7 +26,6 @@ func NewInstance(cfg Config) Instance { } // Init instance - instance := Instance{} instance.Server = initServer(redisConn, cfg) instance.Scheduler = initScheduler(redisConn) instance.Client = initClient(redisConn) diff --git a/task.go b/task.go index 5190f41..ba5b3e0 100644 --- a/task.go +++ b/task.go @@ -1,22 +1,11 @@ package queue import ( - "encoding/json" - "errors" - "fmt" - "github.com/hibiken/asynq" ) // RunTask ... -func RunTask(client *asynq.Client, typename string, data map[string]interface{}, retryTimes int) (*asynq.TaskInfo, error) { - // Convert to []byte - payload, err := json.Marshal(data) - if err != nil { - msg := fmt.Sprintf("task type: %s - error when create new task: %s", typename, err.Error()) - return nil, errors.New(msg) - } - +func (i Instance) RunTask(typename string, payload []byte, retryTimes int) (*asynq.TaskInfo, error) { // Create task and options task := asynq.NewTask(typename, payload) options := make([]asynq.Option, 0) @@ -28,25 +17,18 @@ func RunTask(client *asynq.Client, typename string, data map[string]interface{}, options = append(options, asynq.MaxRetry(retryTimes)) // Enqueue task - return client.Enqueue(task, options...) + return i.Client.Enqueue(task, options...) } // ScheduledTask create new task and run at specific time // cronSpec follow cron expression // https://www.freeformatter.com/cron-expression-generator-quartz.html -func ScheduledTask(scheduler *asynq.Scheduler, typename string, data map[string]interface{}, cronSpec string) (string, error) { - // Convert to []byte - payload, err := json.Marshal(data) - if err != nil { - msg := fmt.Sprintf("task type: %s - error when create new task: %s", typename, err.Error()) - return "", errors.New(msg) - } - +func (i Instance) ScheduledTask(typename string, payload []byte, cronSpec string) (string, error) { // Create task and options task := asynq.NewTask(typename, payload) // TODO: Support options later // options := make([]asynq.Option, 0) - return scheduler.Register(cronSpec, task) + return i.Scheduler.Register(cronSpec, task) }