英文:
running a function periodically in go
问题
我有一个这样的函数:
func run(cmd string) []byte {
out, err := exec.Command(cmd).Output()
if err != nil {
log.Fatal(err)
}
return out
}
我想以这种方式运行这个命令:
run("uptime") // 每5秒运行一次
run("date") // 每10秒运行一次
我想运行这些命令并收集其输出,并对其进行一些操作。在Go语言中,我该如何做到这一点?
英文:
I have a function like this:
func run (cmd string) [] byte {
out,err = exec.Command(cmd).Output()
if error!=nil {
log.Fatal (err)
}
return out
}
I would like to run this command this way
run ("uptime") // run every 5 secs
run ("date") // run every 10 secs
I would like to run these commands and collect its output and do something with it. How would I do this in go?
答案1
得分: 39
使用time.Ticker
。有很多方法可以组织程序,但你可以从一个简单的for循环开始:
uptimeTicker := time.NewTicker(5 * time.Second)
dateTicker := time.NewTicker(10 * time.Second)
for {
select {
case <-uptimeTicker.C:
run("uptime")
case <-dateTicker.C:
run("date")
}
}
如果有可能命令执行时间超过最短间隔,你可能希望在goroutine中运行这些命令,以避免在for循环中积压。或者,每个goroutine可以有自己的for循环和单个Ticker。
英文:
Use a time.Ticker
. There's many ways to structure the program, but you can start with a simple for loop:
uptimeTicker := time.NewTicker(5 * time.Second)
dateTicker := time.NewTicker(10 * time.Second)
for {
select {
case <-uptimeTicker.C:
run("uptime")
case <-dateTicker.C:
run("date")
}
}
You may then want to run the commands in a goroutine if there's a chance they could take longer than your shortest interval to avoid a backlog in the for loop. Alternatively, each goroutine could have its own for loop with a single Ticker.
答案2
得分: 11
func main() {
for range time.Tick(time.Second * 10) {
function_name()
}
}
这个函数每10秒运行一次。
英文:
func main() {
for range time.Tick(time.Second * 10) {
function_name()
}
}
This function runs every 10 sec
答案3
得分: 1
我建议你查看这个包。
https://godoc.org/github.com/robfig/cron
你甚至可以使用秒。
c := cron.New(cron.WithSeconds())
c.AddFunc("*/5 * * * * *", func() { fmt.Println("每5秒测试一次。") })
c.Start()
英文:
I suggest to checkout this package.
https://godoc.org/github.com/robfig/cron
You can even use seconds.
c := cron.New(cron.WithSeconds())
c.AddFunc("*/5 * * * * *", func() { fmt.Println("Testing every 5 seconds.") })
c.Start()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论