1 Star 0 Fork 0

唯哈希 / GUtils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
crontab.go 2.33 KB
一键复制 编辑 原始数据 按行查看 历史
唯哈希 提交于 2023-02-22 19:27 . update
// Refer: https://www.cnblogs.com/jssyjam/p/11910851.html
package gutils
import (
"sync"
"github.com/pkg/errors"
cron "github.com/robfig/cron/v3"
)
// Crontab crontab manager
type Crontab struct {
inner *cron.Cron
ids map[string]cron.EntryID
mutex sync.Mutex
}
// NewCrontab new crontab
// secondsFieldLevel: 0 without,1 required,2 optional
func NewCrontab(secondsFieldLevel uint) *Crontab {
var c *cron.Cron
switch secondsFieldLevel {
case 0:
c = cron.New()
case 1:
c = cron.New(cron.WithSeconds())
case 2:
cron.New(cron.WithParser(cron.NewParser(
cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor,
)))
}
return &Crontab{
inner: c,
ids: make(map[string]cron.EntryID),
}
}
// IDs ...
func (c *Crontab) IDs() []string {
c.mutex.Lock()
defer c.mutex.Unlock()
validIDs := make([]string, 0, len(c.ids))
invalidIDs := make([]string, 0)
for sid, eid := range c.ids {
if e := c.inner.Entry(eid); e.ID != eid {
invalidIDs = append(invalidIDs, sid)
continue
}
validIDs = append(validIDs, sid)
}
for _, id := range invalidIDs {
delete(c.ids, id)
}
return validIDs
}
// Start start the crontab engine
func (c *Crontab) Start() {
c.inner.Start()
}
// Stop stop the crontab engine
func (c *Crontab) Stop() {
c.inner.Stop()
}
// DelByID remove one crontab task
func (c *Crontab) DelByID(id string) {
c.mutex.Lock()
defer c.mutex.Unlock()
eid, ok := c.ids[id]
if !ok {
return
}
c.inner.Remove(eid)
delete(c.ids, id)
}
// AddByID add one crontab task
// id is unique
// spec is the crontab expression
func (c *Crontab) AddByID(id string, spec string, cmd cron.Job) error {
c.mutex.Lock()
defer c.mutex.Unlock()
if _, ok := c.ids[id]; ok {
return errors.Errorf("crontab id exists")
}
eid, err := c.inner.AddJob(spec, cmd)
if err != nil {
return err
}
c.ids[id] = eid
return nil
}
// AddByFunc add function as crontab task
func (c *Crontab) AddByFunc(id string, spec string, f func()) error {
c.mutex.Lock()
defer c.mutex.Unlock()
if _, ok := c.ids[id]; ok {
return errors.Errorf("crontab id exists")
}
eid, err := c.inner.AddFunc(spec, f)
if err != nil {
return err
}
c.ids[id] = eid
return nil
}
// IsExists check the crontab task whether existed with job id
func (c *Crontab) IsExists(jid string) bool {
_, exist := c.ids[jid]
return exist
}
Go
1
https://gitee.com/vhash/gutils.git
git@gitee.com:vhash/gutils.git
vhash
gutils
GUtils
v0.8.1

搜索帮助

53164aa7 5694891 3bd8fe86 5694891