dynamically change ticker interval

余生颓废 提交于 2020-01-23 05:56:08

问题


I would like to change my ticker interval dynamically.

I've written down an example to show you how I did. My use case is something else than an "accelerometer" but I hope that it gives you an idea.

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()
}

What is wrong is that the ticker will always "tick" every seconds and it doesn't accelerate... Any idea?


回答1:


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
}



回答2:


As Nipun Talukdar mentioned, the "for" capture the channel and use the same reference for iterate. it fixed if you use it like this :

playground

package main

import (
    "fmt"
    "log"
    "time"
)

func main() {
    interval := float64(1000)

    ticker := time.NewTicker(time.Duration(interval) * time.Millisecond)
    go func() {
        counter := 1.0
        for {
            select {
            case <-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()
}



回答3:


What about this code:

https://play.golang.org/p/wyOTVxUW5Xj

package main

import (
    "fmt"
    "log"
    "time"
)

func main() {
    startInterval := float64(1000)
    quit := make(chan bool)

    go func() {
        counter := 1.0
        for {
            select {
            case <-time.After(time.Duration(startInterval/counter) * time.Millisecond):
                log.Println("ticker accelerating to " + fmt.Sprint(startInterval/counter) + " ms")
                counter++
            case <-quit:
                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
}


来源:https://stackoverflow.com/questions/36689774/dynamically-change-ticker-interval

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!