My questions is how to schedule running independent non-blocking functions every interval N.
My initial approach is to use go channels within a select statement to receive the values in a non-blocking manner and use time.Sleep(N)
in each function to schedule the call.
In the code snippet below, this only for the first run; however, after the first call, it keeps calling computeY()
repeatedly without respecting the time.Sleep()
call.
package main
import (
"fmt"
"time"
)
var (
x string = ""
y string = ""
)
func computeY(c chan string) {
time.Sleep(10 * time.Second)
fmt.Println("I'm in Y")
y = "this is Y value"
c <- y
}
func computeX(c chan string) {
time.Sleep(1 * time.Second)
x = "this is X value"
c <- x
}
func main() {
xC := make(chan string)
yC := make(chan string)
for {
go computeX(xC)
go computeY(yC)
select {
case x := <-xC:
fmt.Println(fmt.Sprintf("X: %v, Y: %v", x, y))
case y := <-yC:
fmt.Println(fmt.Sprintf("X: %v, Y: %v", x, y))
}
}
}