app/task/store.go

109 lines
2.1 KiB
Go

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("taskname", t.Name).Msg("no ID, using random id")
t.ID = xid.New().String()
}
_, ok := tasks[t.ID]
if ok {
l.Warn().Str("taskname", t.Name).Str("taskid", 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{
Name: util.Caller(2),
ID: xid.New().String(),
}
}
func RunFunc(spec string, cmd func()) error {
th := &Task{
Name: util.Caller(2),
ID: xid.New().String(),
Func: func(carry *interface{}, i ...interface{}) error { cmd(); return nil },
}
t := &_task{Task: th, spec: spec}
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}
id, err := c.AddJob(spec, _t)
_t.id = id
return err
}
func RunTask(spec, id 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}
_id, err := c.AddJob(spec, _t)
_t.id = _id
return err
}
func RunTaskAt(at time.Time, id 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}
_id, err := c.AddJob(spec, _t)
_t.id = _id
return err
}
func RunTaskAfter(d time.Duration, id 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}
_id, err := c.AddJob(spec, _t)
_t.id = _id
return err
}
func Remove(id cron.EntryID) {
c.Remove(id)
}