Golang时间.股票行情,如何从偶数时间戳记开始 [英] Golang time.Ticker, how to begin on even timestamps

查看:59
本文介绍了Golang时间.股票行情,如何从偶数时间戳记开始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在一个时间戳上开始一个 time.Ticker .基本上我想要的是这段代码:

I am attempting to begin a time.Ticker on even timestamps. Basically what I want is for this code:

package main

import (
    "fmt"
    "time"
)

func main() {
    ticker := time.NewTicker(time.Second * 5)

    for i := 0; i < 2; i++ {
        select {
        case <-ticker.C:
            fmt.Println("Time: ", time.Now().Round(time.Second*1))
        }
    }

    ticker.Stop()
}

要始终每隔5秒打印一次:

To always print on an even 5-second interval:

Time:  2015-10-21 12:53:50 -0600 MDT
Time:  2015-10-21 12:53:55 -0600 MDT

对此有一个优雅的解决方案吗?

Is there an elegant solution to this?

推荐答案

您可以延迟股票行情的开始,甚至可以延迟5秒钟:

You can delay the start of your ticker to get pretty close to an even 5 second time:

fiveSec := int64(5 * time.Second)
time.Sleep(time.Duration(fiveSec - (time.Now().UnixNano() % fiveSec)))

ticker := time.NewTicker(time.Second * 5)

或者使用Time方法获得正确延迟的另一种方法:

Or another way to get the correct delay with Time methods:

time.Sleep(time.Now().Truncate(5 * time.Second).Add(5 * time.Second).Sub(time.Now()))

这篇关于Golang时间.股票行情,如何从偶数时间戳记开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆