Search code examples
goconcurrency

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?


Solution

  • 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.