Files
energy-management-system/core/cron/crontab.go
2024-09-03 15:52:38 +08:00

103 lines
2.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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()
}
}