-
Notifications
You must be signed in to change notification settings - Fork 0
/
webgo_command.go
71 lines (62 loc) · 1.68 KB
/
webgo_command.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
package cobra
import (
"github.com/dll02/webgo/framework"
"github.com/robfig/cron/v3"
"log"
)
// SetContainer 设置服务容器
func (c *Command) SetContainer(container framework.Container) {
c.container = container
}
// GetContainer 获取容器
func (c *Command) GetContainer() framework.Container {
return c.Root().container
}
// CronSpec 保存Cron命令的信息,用于展示
type CronSpec struct {
Type string
Cmd *Command
Spec string
ServiceName string
}
func (c *Command) SetParantNull() {
c.parent = nil
}
// AddCronCommand 是用来创建一个Cron任务的
func (c *Command) AddCronCommand(spec string, cmd *Command) {
// cron结构是挂载在根Command上的
root := c.Root()
if root.Cron == nil {
// 初始化cron
root.Cron = cron.New(cron.WithParser(cron.NewParser(cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor)))
root.CronSpecs = []CronSpec{}
}
// 增加说明信息
root.CronSpecs = append(root.CronSpecs, CronSpec{
Type: "normal-cron",
Cmd: cmd,
Spec: spec,
})
// 制作一个rootCommand
var cronCmd Command
ctx := root.Context()
cronCmd = *cmd
cronCmd.args = []string{}
//SetParentNull() 函数,将其上游设置为空,直接在定时器启动的时候调用这个 cronCmd 的 ExecuteCrontext 了。
cronCmd.SetParantNull()
cronCmd.SetContainer(root.GetContainer())
// 增加调用函数
root.Cron.AddFunc(spec, func() {
// 如果后续的command出现panic,这里要捕获
defer func() {
if err := recover(); err != nil {
log.Println(err)
}
}()
err := cronCmd.ExecuteContext(ctx)
if err != nil {
// 打印出err信息
log.Println(err)
}
})
}