任务一完成
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
package timer
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/robfig/cron/v3"
|
||||
)
|
||||
|
||||
// Timer 定时任务管理器
|
||||
type Timer struct {
|
||||
cron *cron.Cron
|
||||
tasks map[string]cron.EntryID
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewTimer 创建定时任务管理器
|
||||
func NewTimer() *Timer {
|
||||
return &Timer{
|
||||
cron: cron.New(cron.WithSeconds()),
|
||||
tasks: make(map[string]cron.EntryID),
|
||||
}
|
||||
}
|
||||
|
||||
// Start 启动定时任务
|
||||
func (t *Timer) Start() {
|
||||
t.cron.Start()
|
||||
}
|
||||
|
||||
// Stop 停止定时任务
|
||||
func (t *Timer) Stop() {
|
||||
t.cron.Stop()
|
||||
}
|
||||
|
||||
// AddTask 添加定时任务
|
||||
func (t *Timer) AddTask(name, spec string, cmd func()) error {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
|
||||
// 如果任务已存在,先删除
|
||||
if id, ok := t.tasks[name]; ok {
|
||||
t.cron.Remove(id)
|
||||
}
|
||||
|
||||
id, err := t.cron.AddFunc(spec, cmd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
t.tasks[name] = id
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemoveTask 删除定时任务
|
||||
func (t *Timer) RemoveTask(name string) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
|
||||
if id, ok := t.tasks[name]; ok {
|
||||
t.cron.Remove(id)
|
||||
delete(t.tasks, name)
|
||||
}
|
||||
}
|
||||
|
||||
// HasTask 检查任务是否存在
|
||||
func (t *Timer) HasTask(name string) bool {
|
||||
t.mu.RLock()
|
||||
defer t.mu.RUnlock()
|
||||
_, ok := t.tasks[name]
|
||||
return ok
|
||||
}
|
||||
|
||||
// ListTasks 列出所有任务
|
||||
func (t *Timer) ListTasks() []string {
|
||||
t.mu.RLock()
|
||||
defer t.mu.RUnlock()
|
||||
|
||||
names := make([]string, 0, len(t.tasks))
|
||||
for name := range t.tasks {
|
||||
names = append(names, name)
|
||||
}
|
||||
return names
|
||||
}
|
||||
Reference in New Issue
Block a user