使用cron运行Go方法
我正在尝试编写一个程序,它将在特定的时间间隔内连续调用一个方法。我正在使用cron库来尝试实现这一点,但当我运行程序时,它只是执行并完成,没有任何输出 下面是我试图做的一个基本例子 非常感谢您的帮助使用cron运行Go方法,go,cron,Go,Cron,我正在尝试编写一个程序,它将在特定的时间间隔内连续调用一个方法。我正在使用cron库来尝试实现这一点,但当我运行程序时,它只是执行并完成,没有任何输出 下面是我试图做的一个基本例子 非常感谢您的帮助 package main import ( "fmt" "github.com/robfig/cron" ) func main() { c := cron.New() c.AddFunc("1 * * * * *", RunEverySecond) c.
package main
import (
"fmt"
"github.com/robfig/cron"
)
func main() {
c := cron.New()
c.AddFunc("1 * * * * *", RunEverySecond)
c.Start()
}
func RunEverySecond() {
fmt.Println("----")
}
如您所见,
c.Start()
在另一个goroutine中运行,因此对c.Start
的调用立即返回
因此,您的程序比您看到的任何输出都要早完成。您可以添加时间。睡眠(1*分钟)之类的内容,或者为此设置一个关闭通道(或者只需
),您可以等待操作系统向您发出信号,例如用户发出的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())
}
主程序包
进口(
“fmt”
“操作系统”
“操作系统/信号”
“时间”
“github.com/robfig/cron”
)
func main(){
c:=cron.New()
c、 AddFunc(“*****”,运行每秒钟)
开始
信号:=接通(切换操作信号)
信号通知(信号、操作系统中断、操作系统终止)
使用外部软件包来实现这一点太过分了,该软件包具备您所需的一切:
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("----")
}
只要确保应用程序始终运行即可,即:
func main() {
cronJob := cron.New()
cronJob.Start()
cronJob.AddFunc("* * * * * ?", PushConfigs)
for {
}
}
或者使用同步等待组执行类似操作
package main
import (
"fmt"
"sync"
"github.com/robfig/cron"
)
// RunEverySecond is to run all the time.
func RunEverySecond() {
fmt.Println("----")
//wg.Done() // Does not release the waitgroup.
}
func main() {
wg := &sync.WaitGroup{}
wg.Add(1)
c := cron.New()
c.AddFunc("@every 1s", RunEverySecond)
c.Start()
wg.Wait() // This guarantees this program never exits so cron can keep running as per the cron interval.
}
选择{}
是永久阻止的最简单方法。这是否回答了您的问题?