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?
Concurrency is not well documented in the go spec and it is one of the most powerful features of the language, the go keyword is the starting point when you are building concurrent software and not procedural software in go.
Yes, the main function runs as a goroutine (the main one). A goroutine is a lightweight thread managed by the Go runtime. go f(x, y, z) starts a new goroutine running f(x, y, z) The evaluation of f, x, y, and z happens in the current goroutine and the execution of f happens in the new goroutine.
A goroutine is a function that executes simultaneously with other goroutines in a program and are lightweight threads managed by Go. A goroutine takes about 2kB of stack space to initialize.
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.
func main() { for range time.Tick(time.Second * 10) { function_name() } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With