douhai5835 2016-01-26 07:51
浏览 45

Golang中的类似计时器功能的警报

Is there any way for designing a timer that expires on a specific future time in Golang ? I mean a timer that expires on 2AM (let the current time be 12AM). I know one way is to use,

 timer(target_future_time - current_time)   

but doesn't seem to be an exact way of doing it (may not be accurate on considering the execution time). Can anyone help please?

  • 写回答

2条回答 默认 最新

  • doutang2017 2016-01-26 08:37
    关注

    In golang,maybe there are two way create ticker,just like the following:

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        //第一种实现方式 
        ticker1 := time.NewTicker(1 * time.Second)
        i := 1
        for c := range ticker1.C {
            i++
            fmt.Println(c.Format("2006/01/02 15:04:05.999999999"))
            if i > 5 {
                ticker1.Stop()
                break
            }
        }
        fmt.Println(time.Now().Format("2006/01/02 15:04:05.999999999"), " 1 Finished.")
    
        //第二种实现方式 
        i = 1
        ticker2 := time.AfterFunc(1*time.Second, func() {
            i++
            fmt.Println(time.Now().Format("2006/01/02 15:04:05.999999999"))
        })
    
        for {
            select {
            case <-ticker2.C:
                fmt.Println("nsmei")
            case <-time.After(3 * time.Second):
                if i <= 5 {
                    ticker2.Reset(1 * time.Second)
                    continue
                }
                goto BRK
            }
        BRK:
            ticker2.Stop()
            break
        }
        fmt.Println(time.Now().Format("2006/01/02 15:04:05.999999999"), " 2 Finished.")
    }
    

    Output:

    2016/01/26 16:46:34.261248567
    2016/01/26 16:46:35.256381743
    2016/01/26 16:46:36.259717152
    2016/01/26 16:46:37.260320837
    2016/01/26 16:46:38.259312704
    2016/01/26 16:46:38.259410752  1 Finished.
    2016/01/26 16:46:39.260604274
    2016/01/26 16:46:42.261091322
    2016/01/26 16:46:45.263136257
    2016/01/26 16:46:48.264193517
    2016/01/26 16:46:51.265655137
    2016/01/26 16:46:53.265722632  2 Finished.
    

    According to the execution,the first is more precise than the second.

    In your case,you can use time.Time.Sub() to calculate the duration,and execute once using the second method,the rest using the first method.

    I hope these help you!

    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度