doutuo6689 2016-01-20 02:37
浏览 123
已采纳

我如何找到计时器启动的剩余时间?

I need to run a function after x seconds, with some ability to control (reset the timer, stop the timer, find time remaining for execution). time.Timer is a close fit - the only thing missing is that it seems to provide no way of finding how much time is left.

What options do I have?

At the moment, I'm thinking of something like:

package main

import "time"

type SecondsTimer struct {
    T       time.Duration
    C       chan time.Time
    control chan time.Duration
    running bool
}

func (s *SecondsTimer) run() {
    for s.T.Seconds() > 0 {
        time.Sleep(time.Second)
        select {
        case f := <-s.control:
            if f > 0 {
                s.T = f
            } else {
                s.running = false
                break
            }
        default:
            s.T = s.T - 1
        }
    }
    s.C <- time.Now()
}
func (s *SecondsTimer) Reset(t time.Duration) {
    if s.running {
        s.control <- t
    } else {
        s.T = t
        go s.run()
    }

}
func (s *SecondsTimer) Stop() {
    if s.running {
        s.control <- 0
    }
}
func NewSecondsTimer(t time.Duration) *SecondsTimer {
    time := SecondsTimer{t, make(chan time.Time), make(chan time.Duration), false}
    go time.run()
    return &time
}

Now I can use s.T.Seconds() as needed.

But I'm wary of race conditions and other such problems. Is this the way to go, or is there something more native I can use?

  • 写回答

1条回答 默认 最新

  • douwei1174 2016-01-20 05:21
    关注

    There is a simpler way. You can still use a time.Timer to accomplish what you want, you just need to keep track of end time.Time:

    type SecondsTimer struct {
        timer *time.Timer
        end   time.Time
    }
    
    func NewSecondsTimer(t time.Duration) *SecondsTimer {
        return &SecondsTimer{time.NewTimer(t), time.Now().Add(t)}
    }
    
    func (s *SecondsTimer) Reset(t time.Duration) {
        s.timer.Reset(t)
        s.end = time.Now().Add(t)
    }
    
    func (s *SecondsTimer) Stop() {
        s.timer.Stop()
    }
    

    so time remaining is easy:

    func (s *SecondsTimer) TimeRemaining() time.Duration {
        return s.end.Sub(time.Now())
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?