0%

Go 保持运行

期望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
package main

import (
"fmt"
"os"
"os/signal"
"time"

"github.com/robfig/cron"
)

func main() {
c := cron.New()
c.AddFunc("* * * * * *", RunEverySecond)
go c.Start()
sig := make(chan os.Signal)
signal.Notify(sig, os.Interrupt, os.Kill)
<-sig

}

func RunEverySecond() {
fmt.Printf("%v\n", time.Now())
}

关键部分在这一块代码,还没吃透。

1
2
3
sig := make(chan os.Signal)
signal.Notify(sig, os.Interrupt, os.Kill)
<-sig

另外一个方法 select

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package main

import (
"fmt"
"time"
)

func main() {
go forever()
select {} // block forever
}

func forever() {
for {
fmt.Printf("%v+\n", time.Now())
time.Sleep(time.Second)
}
}

更多方法见 how-best-do-i-keep-a-long-running-go-program-running