This commit is contained in:
孟帅
2022-11-24 23:37:34 +08:00
parent 4ffe54b6ac
commit 29bda0dcdd
1487 changed files with 97869 additions and 96539 deletions

View File

@@ -0,0 +1,199 @@
// Package crons
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package crons
import (
"context"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gcron"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/os/gtime"
"hotgo/internal/consts"
"hotgo/internal/dao"
"hotgo/internal/model/entity"
"strings"
"sync"
)
var (
// 添加新的任务时只需实现cronStrategy接口并加入到cronList即可
cronList = []cronStrategy{
Test, // 测试无参任务
Test2, // 测试有参任务
Monitor, // 监控
}
inst = new(tasks)
)
type cronStrategy interface {
GetName() string
Execute(ctx context.Context)
}
type tasks struct {
list []*TaskItem
sync.RWMutex
}
type TaskItem struct {
Pattern string // 表达式参考https://goframe.org/pages/viewpage.action?pageId=30736411
Name string // 唯一的任务名称
Params string // 函数参数,多个用,隔开
Fun gcron.JobFunc // 执行的函数接口
Policy int64 // 策略 1并行 2单例 3单次 4多次
Count int // 执行次数仅Policy=4时有效
}
func init() {
for _, cron := range cronList {
inst.Add(&TaskItem{
Name: cron.GetName(),
Fun: cron.Execute,
})
}
}
func StopALL() {
for _, v := range gcron.Entries() {
gcron.Remove(v.Name)
}
}
// StartALL 启动任务
func StartALL(sysCron []*entity.SysCron) error {
var (
err error
ct = gctx.New()
)
if len(sysCron) == 0 {
g.Log().Info(ct, "没有可用的定时任务")
return nil
}
for _, cron := range sysCron {
f := inst.Get(cron.Name)
if f == nil {
return gerror.Newf("该任务没有加入任务列表:%v", cron.Name)
}
// 没有则添加
if gcron.Search(cron.Name) == nil {
var (
t *gcron.Entry
ctx = context.WithValue(gctx.New(), consts.CronArgsKey, strings.Split(cron.Params, consts.CronSplitStr))
)
switch cron.Policy {
case consts.CronPolicySame:
t, err = gcron.Add(ctx, cron.Pattern, f.Fun, cron.Name)
case consts.CronPolicySingle:
t, err = gcron.AddSingleton(ctx, cron.Pattern, f.Fun, cron.Name)
case consts.CronPolicyOnce:
t, err = gcron.AddOnce(ctx, cron.Pattern, f.Fun, cron.Name)
case consts.CronPolicyTimes:
if f.Count <= 0 {
f.Count = 1
}
t, err = gcron.AddTimes(ctx, cron.Pattern, int(cron.Count), f.Fun, cron.Name)
default:
return gerror.Newf("使用无效的策略, cron.Policy=%v", cron.Policy)
}
if err != nil {
return err
}
if t == nil {
return gerror.New("启动任务失败")
}
}
gcron.Start(cron.Name)
// 执行完毕,单次和多次执行的任务更新状态
if cron.Policy == consts.CronPolicyOnce || cron.Policy == consts.CronPolicyTimes {
_, err = dao.SysCron.Ctx(ct).Where("id", cron.Id).
Data(g.Map{"status": consts.StatusDisable, "updated_at": gtime.Now()}).
Update()
if err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return err
}
}
}
g.Log().Info(ct, "定时任务启动完毕...")
return nil
}
// Stop 停止单个任务
func Stop(sysCron *entity.SysCron) error {
return nil
}
// Once 立即执行一次某个任务
func Once(sysCron *entity.SysCron) error {
return nil
}
// Delete 删除任务
func Delete(sysCron *entity.SysCron) error {
// ...
return Stop(sysCron)
}
// Start 启动单个任务
func Start(sysCron *entity.SysCron) error {
return nil
}
// Add 添加任务
func (t *tasks) Add(task *TaskItem) *tasks {
if task.Name == "" || task.Fun == nil {
return t
}
t.Lock()
defer t.Unlock()
t.list = append(t.list, task)
return t
}
// Get 找到任务
func (t *tasks) Get(name string) *TaskItem {
if len(t.list) == 0 {
return nil
}
for _, item := range t.list {
if item.Name == name {
return item
}
}
return nil
}
// Del 删除任务
func (t *tasks) Del(name string) (newList []*TaskItem) {
if len(t.list) == 0 {
return nil
}
t.Lock()
defer t.Unlock()
for _, item := range t.list {
if item.Name == name {
continue
}
newList = append(newList, item)
}
return newList
}

View File

@@ -0,0 +1,75 @@
// Package crons
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package crons
import (
"context"
"github.com/gogf/gf/v2/os/gtime"
"github.com/shirou/gopsutil/load"
"github.com/shirou/gopsutil/net"
"hotgo/internal/global"
"hotgo/internal/model"
"hotgo/utility/format"
"runtime"
"sync"
)
// Monitor 监控
var Monitor = &cMonitor{name: "monitor"}
type cMonitor struct {
name string
sync.RWMutex
}
func (c *cMonitor) GetName() string {
return c.name
}
// Execute 执行任务
func (c *cMonitor) Execute(ctx context.Context) {
c.Lock()
defer c.Unlock()
c.NetIO()
c.loadAvg()
}
func (c *cMonitor) loadAvg() {
pl, _ := load.Avg()
counter := model.LoadAvgStats{
Time: gtime.Now(),
Avg: pl.Load1,
Ratio: pl.Load1 / (float64(runtime.NumCPU()) * 2) * 100,
}
global.MonitorData.LoadAvg = append(global.MonitorData.LoadAvg, &counter)
if len(global.MonitorData.LoadAvg) > 10 {
global.MonitorData.LoadAvg = append(global.MonitorData.LoadAvg[:0], global.MonitorData.LoadAvg[(1):]...)
}
}
func (c *cMonitor) NetIO() {
var counter model.NetIOCounters
ni, _ := net.IOCounters(true)
counter.Time = gtime.Now()
for _, v := range ni {
counter.BytesSent += v.BytesSent
counter.BytesRecv += v.BytesRecv
}
if len(global.MonitorData.NetIO) > 0 {
lastNetIO := global.MonitorData.NetIO[len(global.MonitorData.NetIO)-1]
sub := counter.Time.Sub(lastNetIO.Time).Seconds()
counter.Down = format.Round2Float64((float64(counter.BytesRecv - lastNetIO.BytesRecv)) / sub)
counter.UP = format.Round2Float64((float64(counter.BytesSent - lastNetIO.BytesSent)) / sub)
}
global.MonitorData.NetIO = append(global.MonitorData.NetIO, &counter)
if len(global.MonitorData.NetIO) > 10 {
global.MonitorData.NetIO = append(global.MonitorData.NetIO[:0], global.MonitorData.NetIO[(1):]...)
}
}

View File

@@ -0,0 +1,29 @@
// Package crons
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package crons
import (
"context"
"github.com/gogf/gf/v2/frame/g"
"time"
)
// Test 测试任务
var Test = &cTest{name: "test"}
type cTest struct {
name string
}
func (c *cTest) GetName() string {
return c.name
}
// Execute 执行任务
func (c *cTest) Execute(ctx context.Context) {
g.Log().Infof(ctx, "cron test Execute:%v", time.Now())
}

View File

@@ -0,0 +1,46 @@
// Package crons
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package crons
import (
"context"
"github.com/gogf/gf/v2/frame/g"
"hotgo/internal/consts"
"time"
)
// Test2 测试2任务
var Test2 = &cTest2{name: "test2"}
type cTest2 struct {
name string
}
func (c *cTest2) GetName() string {
return c.name
}
// Execute 执行任务
func (c *cTest2) Execute(ctx context.Context) {
args, ok := ctx.Value(consts.CronArgsKey).([]string)
if !ok {
g.Log().Warning(ctx, "参数解析失败!")
return
}
if len(args) != 3 {
g.Log().Warning(ctx, "test2 传入参数不正确!")
return
}
var (
name = args[0]
age = args[1]
msg = args[2]
)
g.Log().Infof(ctx, "cron test2 Execute:%v, name:%v, age:%v, msg:%v", time.Now(), name, age, msg)
}