douju5062 2016-04-18 09:11
浏览 38
已采纳

动态更改股票行情间隔

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?

  • 写回答

3条回答 默认 最新

  • doswy02440 2016-04-19 06:14
    关注

    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条)

报告相同问题?

悬赏问题

  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录