change public funcs to method

This commit is contained in:
Nam Huynh 2021-11-30 22:21:26 +07:00
parent fcdcaaaa3c
commit 61c1ac19a4
2 changed files with 6 additions and 23 deletions

View File

@ -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)

26
task.go
View File

@ -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)
}