Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

running a function periodically in go

Tags:

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?

like image 349
NinjaGaiden Avatar asked Nov 01 '16 16:11

NinjaGaiden


People also ask

What is go keyword 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.

Is main function a go routine?

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.

What are go routines?

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.


2 Answers

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.

like image 81
JimB Avatar answered Sep 28 '22 08:09

JimB


func main() {     for range time.Tick(time.Second * 10) {         function_name()     } } 
like image 37
RITESH Avatar answered Sep 28 '22 06:09

RITESH