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?