dynamically change ticker interval
Following the answer to @fzerorubigd but a little more complete.
As said before, we can't use the range
for this case, because the range
loop caches the variable to be lopped and then it can't be overwritten (example here: http://play.golang.org/p/yZvrgURz4o )
Then, we should use a for
-select
combination loop. Hereafter the working solution:
http://play.golang.org/p/3uJrAIhnTQ
package main
import (
"time"
"log"
"fmt"
)
func main() {
start_interval := float64(1000)
quit := make(chan bool)
go func(){
ticker := time.NewTicker(time.Duration(start_interval) * time.Millisecond)
counter := 1.0
for {
select {
case <-ticker.C:
log.Println("ticker accelerating to " + fmt.Sprint(start_interval/counter) + " ms")
ticker.Stop()
ticker = time.NewTicker(time.Duration(start_interval/counter) * time.Millisecond)
counter++
case <-quit:
ticker.Stop()
log.Println("..ticker stopped!")
return
}
}
}()
time.Sleep(5 * time.Second)
log.Println("stopping ticker...")
quit<-true
time.Sleep(500 * time.Millisecond) // just to see quit messages
}