Skip to content

Commit 29117d2

Browse files
committed
misc: use goroutine & chan & sync.waitgroup
1 parent ad4b601 commit 29117d2

File tree

1 file changed

+38
-18
lines changed

1 file changed

+38
-18
lines changed

main.go

Lines changed: 38 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
log "github.com/sirupsen/logrus"
99
"github.com/spf13/viper"
1010
"os/exec"
11+
"sync"
1112
"time"
1213
)
1314

@@ -16,7 +17,12 @@ type CrontabCmdList struct {
1617
Crontab string
1718
}
1819

19-
var ccl []CrontabCmdList
20+
21+
var (
22+
chanPool = make(chan int, 3)
23+
wg sync.WaitGroup
24+
ccl []CrontabCmdList
25+
)
2026

2127
func init() {
2228
initLog()
@@ -46,35 +52,49 @@ func main() {
4652

4753
// 遍历任务
4854
for _, v := range ccl {
49-
55+
wg.Add(1)
5056
Crontab := v.Crontab
5157
Cmd := v.Cmd
52-
5358
// 添加所有配置的 Crontab
54-
id, err := c.AddFunc(Crontab, func() {
59+
go addCrontabTask(c, Crontab, Cmd)
60+
}
5561

56-
f, err := exec.Command("bash", "-c", Cmd).Output()
62+
// 等待所有任务添加完毕
63+
wg.Wait()
5764

58-
if err != nil {
59-
log.Error(err.Error())
60-
}
61-
log.Println("执行命令:", Cmd, "输出:", string(f))
65+
close(chanPool)
66+
defer c.Stop()
67+
c.Start()
68+
69+
fmt.Println("程序已启动,请不要关闭终端")
70+
71+
select {}
72+
}
6273

63-
})
74+
func addCrontabTask(c *cron.Cron, Crontab , Cmd string) {
75+
76+
chanPool <- 1
77+
78+
id, err := c.AddFunc(Crontab, func() {
79+
80+
f, err := exec.Command("bash", "-c", Cmd).Output()
6481

6582
if err != nil {
66-
fmt.Println("定时任务启动错误:", err, id, Crontab, Cmd)
67-
} else {
68-
fmt.Println("已启动监听的定时任务: ", id, "表达式:", Crontab, "命令:", Cmd)
83+
log.Error(err.Error())
6984
}
85+
log.Println("执行命令:", Cmd, "输出:", string(f))
7086

71-
}
87+
})
7288

73-
c.Start()
74-
75-
fmt.Println("Start ing ")
89+
if err != nil {
90+
fmt.Println("定时任务启动错误:", err, id, Crontab, Cmd)
91+
} else {
92+
fmt.Println("已启动监听的定时任务: ", id, "表达式:", Crontab, "命令:", Cmd)
93+
}
7694

77-
select {}
95+
//time.Sleep(time.Second)
96+
<-chanPool
97+
wg.Done()
7898
}
7999

80100
func initLog() {

0 commit comments

Comments
 (0)