使用cron运行Go方法

AFr*_*ser 3 cron go

我正在尝试编写一个程序,它会在某个时间间隔内不断调用方法.我正在使用cron库来尝试实现这一点,但是当我运行程序时,它只执行并完成任何输出.

以下是我正在尝试做的基本示例.

非常感谢!

package main

import (
    "fmt"
    "github.com/robfig/cron"
)

func main() {
    c := cron.New()
    c.AddFunc("1 * * * * *", RunEverySecond)
    c.Start()
}

func RunEverySecond() {
    fmt.Println("----")
}
Run Code Online (Sandbox Code Playgroud)

Len*_*enW 11

您可以等待操作系统向您发出信号,例如来自用户的CTRL-C.你的cron表达式也适用于每一分钟,即只有秒== 1.

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())
}
Run Code Online (Sandbox Code Playgroud)


ser*_*jja 5

正如你可以看到c.Start()在另一个goroutine中运行,所以调用c.Start立即返回.https://github.com/robfig/cron/blob/master/cron.go#L125

因此,您的程序比您看到任何输出更早完成.您可以time.Sleep(1 * minute)为此添加类似或具有关闭通道的东西(或者只是<-make(chan struct{})为了永远等待)

  • `select {}`是永远阻止的最简单方法. (3认同)

Dav*_*e C 5

为此使用外部包是矫枉过正的,该time包具有您需要的一切:

package main

import (
    "fmt"
    "time"
)

func main() {
    go func() {
        c := time.Tick(1 * time.Second)
        for range c {
            // Note this purposfully runs the function
            // in the same goroutine so we make sure there is
            // only ever one. If it might take a long time and
            // it's safe to have several running just add "go" here.
            RunEverySecond()
        }
    }()

    // Other processing or the rest of your program here.
    time.Sleep(5 * time.Second)

    // Or to block forever:
    //select {}
    // However, if doing that you could just stick the above for loop
    // right here without dropping it into a goroutine.
}

func RunEverySecond() {
    fmt.Println("----")
}
Run Code Online (Sandbox Code Playgroud)

playground