Go中的CRON作业未按预期运行

huangapple go评论75阅读模式
英文:

CRON job in Go not running as expected

问题

这是我的代码:

package main

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

func main() {
    c := cron.New()
    c.AddFunc("@every 3m", func() { fmt.Println("每隔3分钟") })
    c.Start()
    fmt.Println("完成")
}

问题是,当我使用go run运行代码时,它只打印出完成然后退出。我只是想每隔3分钟打印一次函数。

英文:

Here is my code:

package main

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

func main() {
    c := cron.New()
    c.AddFunc("@every 3m", func() { fmt.Println("Every 3 min") })
    c.Start()
    fmt.Println("Done")
}

The problem is when I run the code using go run it just prints Done then exits. I am just trying to print the function every 3 minute.

答案1

得分: 3

扩展@Flimzy的答案,如果你希望你的程序保持空闲状态,只需添加select {}即可。

你的代码应该像这样:

func main() {
    c := cron.New()
    c.AddFunc("@every 3m", func() { fmt.Println("Every 3 min") })
    c.Start()
    fmt.Println("Done")
    select {}
}
英文:

Extending on @Flimzy answer, if you want your program to sit and do nothing, just add select {} to it

Your code would be something like this:

func main() {
    c := cron.New()
    c.AddFunc("@every 3m", func() { fmt.Println("Every 3 min") })
    c.Start()
    fmt.Println("Done")
    select {}
}

答案2

得分: 2

你的代码做了以下几件事情:

  1. 初始化了一个新的 cron 实例:

     c := cron.New()
    
  2. 添加了一个 cron 作业:

     c.AddFunc("@every 3m", func() { fmt.Println("Every 3 min") })
    
  3. 在一个新的 goroutine(后台)中启动了 cron 实例:

     c.Start()
    
  4. 打印了 "Done":

     fmt.Println("Done")
    
  5. 然后退出。

如果你希望程序继续运行,你需要让它执行一些使其保持运行的操作。如果没有其他需要程序执行的任务,你可以让它等待一个永远不会结束的任务完成。可以参考这个答案中的一些建议。

英文:

Your code does this:

  1. Initiates a new cron instance:

     c := cron.New()
    
  2. Adds a cron job:

     c.AddFunc("@every 3m", func() { fmt.Println("Every 3 min") })
    
  3. Starts the cron instance in a new goroutine (in the background):

     c.Start()
    
  4. Prints "Done":

     fmt.Println("Done")
    
  5. Then exits.

If you want your program to keep running, you need to make it do something that keeps it running. If there is nothing else you need your program to do, just have it wait for something to finish that never finishes. See this answer for some suggestions along those lines.

huangapple
  • 本文由 发表于 2017年4月10日 10:18:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/43314088.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定