我需要在x幾秒鐘后運行一個函數(shù),并具有一定的控制能力(重置計時器,停止計時器,找到剩余的執(zhí)行時間)。time.Timer非常合適 - 唯一缺少的是它似乎無法找到還剩多少時間。我有哪些選擇?目前,我正在考慮類似的事情:package mainimport "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}現(xiàn)在我可以s.T.Seconds()根據(jù)需要使用了。但我對競爭條件和其他此類問題持謹慎態(tài)度。這是要走的路,還是我可以使用更原生的東西?
1 回答

慕村9548890
TA貢獻1884條經(jīng)驗 獲得超4個贊
有一個更簡單的方法。你仍然可以使用 atime.Timer來完成你想要的,你只需要跟蹤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()
}
所以剩下的時間很容易:
func (s *SecondsTimer) TimeRemaining() time.Duration {
return s.end.Sub(time.Now())
}
- 1 回答
- 0 關(guān)注
- 339 瀏覽
添加回答
舉報
0/150
提交
取消