package task import ( "fmt" "sync" "time" cron "github.com/robfig/cron/v3" "github.com/rs/xid" "kumoly.io/kumoly/app/util" ) var stlok sync.Mutex var tasks = map[string]*Task{} func AddTask(t *Task) { stlok.Lock() defer stlok.Unlock() if t.ID == "" { l.Warn().Str("task_id", t.ID).Msg("no ID, using random id") t.ID = xid.New().String() } _, ok := tasks[t.ID] if ok { l.Warn().Str("task_id", t.ID).Msg("task is already in store, skipping") } else { tasks[t.ID] = t } } func GetTasks() map[string]*Task { return tasks } func GetTask(id string) *Task { return tasks[id] } func NewTask() *Task { return &Task{ ID: xid.New().String(), } } func RunFunc(spec string, cmd func()) error { th := &Task{ ID: xid.New().String(), Func: func(carry *interface{}, i ...interface{}) error { cmd(); return nil }, } t := &_task{Task: th, spec: spec, name: util.Caller(2)} id, err := c.AddJob(spec, t) t.id = id return err } func AddAndRunTask(spec string, t *Task, args ...interface{}) error { AddTask(t) _t := &_task{Task: t, args: args, spec: spec, name: t.ID} id, err := c.AddJob(spec, _t) _t.id = id return err } func RunTask(spec, id, name string, args ...interface{}) error { t := GetTask(id) if t == nil { return fmt.Errorf("no task with id") } _t := &_task{Task: t, args: args, spec: spec, name: name} _id, err := c.AddJob(spec, _t) _t.id = _id return err } func RunTaskAt(at time.Time, id, name string, args ...interface{}) error { next := time.Until(at).Round(time.Second) if next < 0 { return fmt.Errorf("%v is passed by %s", at, next) } t := GetTask(id) if t == nil { return fmt.Errorf("no task with id") } spec := "@every " + next.String() _t := &_task{Task: t, args: args, spec: spec, once: true, name: name} _id, err := c.AddJob(spec, _t) _t.id = _id return err } func RunTaskAfter(d time.Duration, id, name string, args ...interface{}) error { t := GetTask(id) if t == nil { return fmt.Errorf("no task with id") } spec := "@every " + d.String() _t := &_task{Task: t, args: args, spec: spec, once: true, name: name} _id, err := c.AddJob(spec, _t) _t.id = _id return err } func Remove(id cron.EntryID) { c.Remove(id) }