I am trying to do some CRUD operations which takes longer time. I have come up with the sample playground to demonstrate my problem:
package main
import (
"fmt"
"math/rand"
"time"
)
func call(s int) {
fmt.Println(s)
}
func get() int {
num := rand.Intn(20-10) + 5
return num
}
func main() {
call(1)
ticker := time.NewTicker(1000 * time.Millisecond)
stop := make(chan bool, 1)
check := make(chan string, 1)
go func() {
for {
select {
case <-stop:
check <- "done"
fmt.Println("stopped")
return
case <-ticker.C:
randInt := get()
if randInt == 11 {
call(randInt)
stop <- true
} else {
call(randInt)
}
}
}
}()
//fmt.Println(<-stop)
}
- It's a http request
- At the end of the request, I do return with 202 http then fire a go routine.
- Purpose of go routine, to check whether the requested entity is created/deleted/updated/failed than
in progress
- Demo program runs until it gets random number 11 i.e similar to getting one of the desired status as in point 3.
- I feel that there could be a chance where random number never meets 11 for quite long time.(if range is 1 million) So I want to cancel the ticker after 10 func calls.
How do I do this?
Are correct things used i.e ticker, goroutine
. Kindly suggest.
Unfortunately, I couldn't decode after referring several forums, posts. Confused more with context, timer
and all.