我想动态更改我的股票行情间隔。
我写下了一个例子来向您展示我的工作方式。我的用例不是“加速度计”,而是希望它能给您一个构想。
http://play.golang.org/p/6ANFnoE6pA
package main import ( "time" "log" "fmt" ) func main() { interval := float64(1000) ticker := time.NewTicker(time.Duration(interval) * time.Millisecond) go func(){ counter := 1.0 for range ticker.C { log.Println("ticker accelerating to " + fmt.Sprint(interval/counter) + " ms") ticker = time.NewTicker(time.Duration(interval/counter) * time.Millisecond) counter++ } log.Println("stopped") }() time.Sleep(5 * time.Second) log.Println("stopping ticker") ticker.Stop() }
出问题的是,股票报价器总是每秒钟都在“滴答”,并且不会加速…有什么想法吗?
遵循对@fzerorubigd的回答,但更加完整。
range
然后,我们应该使用for- select组合循环。以下是工作解决方案:
for
select
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 }