app/task/store.go

107 lines
2.2 KiB
Go
Raw Normal View History

2021-12-16 04:11:33 +00:00
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 == "" {
2021-12-19 06:02:39 +00:00
l.Warn().Str("task_id", t.ID).Msg("no ID, using random id")
2021-12-16 04:11:33 +00:00
t.ID = xid.New().String()
}
_, ok := tasks[t.ID]
if ok {
2021-12-19 06:02:39 +00:00
l.Warn().Str("task_id", t.ID).Msg("task is already in store, skipping")
2021-12-16 04:11:33 +00:00
} 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{
2021-12-19 06:02:39 +00:00
ID: xid.New().String(),
2021-12-16 04:11:33 +00:00
}
}
func RunFunc(spec string, cmd func()) error {
th := &Task{
ID: xid.New().String(),
Func: func(carry *interface{}, i ...interface{}) error { cmd(); return nil },
}
2021-12-19 06:02:39 +00:00
t := &_task{Task: th, spec: spec, name: util.Caller(2)}
2021-12-16 04:11:33 +00:00
id, err := c.AddJob(spec, t)
t.id = id
return err
}
func AddAndRunTask(spec string, t *Task, args ...interface{}) error {
AddTask(t)
2021-12-19 06:02:39 +00:00
_t := &_task{Task: t, args: args, spec: spec, name: t.ID}
2021-12-16 04:11:33 +00:00
id, err := c.AddJob(spec, _t)
_t.id = id
return err
}
2021-12-19 06:02:39 +00:00
func RunTask(spec, id, name string, args ...interface{}) error {
2021-12-16 04:11:33 +00:00
t := GetTask(id)
if t == nil {
return fmt.Errorf("no task with id")
}
2021-12-19 06:02:39 +00:00
_t := &_task{Task: t, args: args, spec: spec, name: name}
2021-12-16 04:11:33 +00:00
_id, err := c.AddJob(spec, _t)
_t.id = _id
return err
}
2021-12-19 06:02:39 +00:00
func RunTaskAt(at time.Time, id, name string, args ...interface{}) error {
2021-12-16 04:11:33 +00:00
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()
2021-12-19 06:02:39 +00:00
_t := &_task{Task: t, args: args, spec: spec, once: true, name: name}
2021-12-16 04:11:33 +00:00
_id, err := c.AddJob(spec, _t)
_t.id = _id
return err
}
2021-12-19 06:02:39 +00:00
func RunTaskAfter(d time.Duration, id, name string, args ...interface{}) error {
2021-12-16 04:11:33 +00:00
t := GetTask(id)
if t == nil {
return fmt.Errorf("no task with id")
}
spec := "@every " + d.String()
2021-12-19 06:02:39 +00:00
_t := &_task{Task: t, args: args, spec: spec, once: true, name: name}
2021-12-16 04:11:33 +00:00
_id, err := c.AddJob(spec, _t)
_t.id = _id
return err
}
func Remove(id cron.EntryID) {
c.Remove(id)
}