-
Notifications
You must be signed in to change notification settings - Fork 1
/
model.go
84 lines (73 loc) · 2.64 KB
/
model.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package job
import (
"sync"
"time"
"github.com/robfig/cron/v3"
"github.com/snowlyg/iris-admin/server/zap_server"
"gorm.io/gorm"
)
// Job
type Job struct {
gorm.Model
BaseJob
}
type BaseJob struct {
EntryId cron.EntryID `gorm:"uniqueIndex:entry_id;column:entry_id;type:char(15);default:0" json:"entryId" binding:"required"` // 任务id
Name string `gorm:"uniqueIndex:service_name;column:name;type:varchar(30);default:''" json:"name" binding:"required"` // 任务名称
Spec string `gorm:"column:spec;type:varchar(10);default:''" json:"spec" binding:"required"` // 任务cron 配置
Status string `gorm:"column:status;type:varchar(10);default:''" json:"status" binding:"required"` // 任务状态 running stoped
Desc string `gorm:"column:desc;type:varchar(50);default:''" json:"desc"` // 任务描述
Count int `gorm:"column:count;type:bigint;default:0" json:"count"` // 运行记录
Message string `gorm:"column:message;type:varchar(2000);default:''" json:"message"` // 执行信息
LastAt *time.Time `json:"lastAt"` // 运行时间
}
// Create 添加
func (item *Job) Create(db *gorm.DB) (uint, error) {
err := db.Model(item).Create(item).Error
if err != nil {
zap_server.ZAPLOG.Error(err.Error())
return 0, err
}
return item.ID, nil
}
// Update 更新
func (item *Job) Update(db *gorm.DB, scopes ...func(db *gorm.DB) *gorm.DB) error {
data := map[string]interface{}{
"status": item.Status,
"desc": item.Desc,
"name": item.Name,
"spec": item.Spec,
}
err := db.Model(item).Scopes(scopes...).Updates(data).Error
if err != nil {
zap_server.ZAPLOG.Error(err.Error())
return err
}
return nil
}
// Delete 删除
func (item *Job) Delete(db *gorm.DB, scopes ...func(db *gorm.DB) *gorm.DB) error {
err := db.Model(item).Unscoped().Scopes(scopes...).Delete(item).Error
if err != nil {
zap_server.ZAPLOG.Error(err.Error())
return err
}
return nil
}
var BuiltinJobs = &BuiltinJob{jobs: make(map[string]cron.Job, 100)}
// 定义内置任务
type BuiltinJob struct {
sync.RWMutex
jobs map[string]cron.Job
}
func (bj *BuiltinJob) AddBuiltinJob(name, spec, desc string, job cron.Job) error {
BuiltinJobs.RLock()
defer BuiltinJobs.RUnlock()
bj.jobs[name] = job
return syncJob(name, spec, desc, job)
}
func (bj *BuiltinJob) GetBuiltinJob(name string) cron.Job {
BuiltinJobs.RLock()
defer BuiltinJobs.RUnlock()
return bj.jobs[name]
}