Skip to content

保持 Go 程序持续运行

Published: at 05:12 AMSuggest Changes

期望 go 的程序一直运行不中断

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())
}

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

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

另外一个方法 select

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


Previous Post
Go 语言 Cron 定时任务详解
Next Post
Go 语言解决中文乱码问题