NinjaGaiden
NinjaGaiden

Reputation: 3146

running a function periodically in 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?

Upvotes: 29

Views: 24832

Answers (3)

RITESH
RITESH

Reputation: 153

func main() {
    for range time.Tick(time.Second * 10) {
        function_name()
    }
}

This function runs every 10 sec

Upvotes: 14

Kristaps J.
Kristaps J.

Reputation: 352

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()

Upvotes: 3

Mr_Pink
Mr_Pink

Reputation: 109416

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.

Upvotes: 41

Related Questions