running a function periodically in go

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

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 &lt;-uptimeTicker.C:
		run(&quot;uptime&quot;)
	case &lt;-dateTicker.C:
		run(&quot;date&quot;)
	}
}

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(&quot;*/5 * * * * *&quot;, func() { fmt.Println(&quot;Testing every 5 seconds.&quot;) })
c.Start()

huangapple
  • 本文由 发表于 2016年11月2日 00:26:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/40364270.html
匿名

发表评论

匿名网友

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

确定