103 lines
2.2 KiB
Go
103 lines
2.2 KiB
Go
package cron
|
||
|
||
import (
|
||
"energy-management-system/global"
|
||
"energy-management-system/utils/exception"
|
||
"energy-management-system/utils/recovery"
|
||
"fmt"
|
||
"github.com/robfig/cron/v3"
|
||
"os"
|
||
"reflect"
|
||
"runtime"
|
||
"time"
|
||
)
|
||
|
||
var funs customFunc
|
||
var jobs customJob
|
||
|
||
type customFunc struct {
|
||
Specs []string
|
||
Func []func()
|
||
}
|
||
|
||
func (c *customFunc) register(spec string, f func()) {
|
||
c.Specs = append(c.Specs, spec)
|
||
c.Func = append(c.Func, f)
|
||
}
|
||
|
||
// RegisterCronFunc 参数:规则(s m h d m w),函数
|
||
func RegisterCronFunc(spec string, f func()) {
|
||
funs.register(spec, f)
|
||
}
|
||
|
||
func RegisterRuntimeCronFunc(spec string, f func()) {
|
||
_, err := global.Cron.AddFunc(spec, wrap(f))
|
||
if err != nil {
|
||
exception.PEM(err, "添加定时func失败")
|
||
return
|
||
}
|
||
}
|
||
|
||
type customJob struct {
|
||
Specs []string
|
||
Jobs []cron.Job
|
||
}
|
||
|
||
func (c *customJob) register(spec string, f cron.Job) {
|
||
c.Specs = append(c.Specs, spec)
|
||
c.Jobs = append(c.Jobs, f)
|
||
}
|
||
|
||
// RegisterCronJob 参数:规则(s m h d m w),函数
|
||
func RegisterCronJob(spec string, job cron.Job) {
|
||
jobs.register(spec, job)
|
||
}
|
||
func RegisterRuntimeCronJob(spec string, job cron.Job) {
|
||
_, err := global.Cron.AddJob(spec, job)
|
||
if err != nil {
|
||
exception.PEM(err, "添加定时job失败")
|
||
return
|
||
}
|
||
}
|
||
|
||
func InitCron() {
|
||
// 设置时区
|
||
loc, _ := time.LoadLocation("Asia/Shanghai")
|
||
|
||
location := cron.WithLocation(loc)
|
||
// 开启秒
|
||
withSeconds := cron.WithSeconds()
|
||
// 自定义规则
|
||
withParser := cron.WithParser(cron.NewParser(cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor))
|
||
|
||
// cron初始化
|
||
c := cron.New(location, withSeconds, withParser)
|
||
|
||
// 初始化预定Job
|
||
for idx, spec := range jobs.Specs {
|
||
_, err := c.AddJob(spec, jobs.Jobs[idx])
|
||
//_, err := c.AddFunc(v, wrap(servers.Func[k]))
|
||
if err != nil {
|
||
fmt.Printf("[-]注册初始定时job失败: %s \n", err)
|
||
os.Exit(1)
|
||
}
|
||
}
|
||
// 初始化预定func
|
||
for idx, spec := range funs.Specs {
|
||
_, err := c.AddFunc(spec, wrap(funs.Func[idx]))
|
||
if err != nil {
|
||
fmt.Printf("[-]注册初始定时func失败: %s \n", err)
|
||
os.Exit(1)
|
||
}
|
||
}
|
||
global.Cron = c
|
||
c.Start()
|
||
}
|
||
|
||
func wrap(f func()) func() {
|
||
return func() {
|
||
defer recovery.CronRecovery(runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name())
|
||
f()
|
||
}
|
||
}
|