-
Notifications
You must be signed in to change notification settings - Fork 18.8k
Closed
Labels
Milestone
Description
It would be good to be able to dynamically change the Ticker duration. Even if it is not super accurate in between the change in duration.
[untested] It should behave something like this: (but more accurate/intelligent):
type Ticker struct {
C chan time.Time
stop chan struct{}
unleak chan struct{}
stopped bool
sync.Mutex
tt *time.Ticker
}
func NewTicker(d time.Duration) *Ticker {
c := make(chan time.Time, 1)
t := &Ticker{
C: c,
stop: make(chan struct{}),
unleak: make(chan struct{}),
tt: time.NewTicker(d),
stopped: false,
}
go func() {
for {
select {
case now := <-t.tt.C:
t.C <- now
case <-t.unleak:
return
case <-t.stop:
return
}
}
}()
return t
}
func (t *Ticker) Stop() {
t.Lock()
defer t.Unlock()
if t.stopped {
return
}
t.stop <- struct{}{}
t.tt.Stop()
t.stopped = true
}
func (t *Ticker) SetDuration(d time.Duration) {
t.Lock()
defer t.Unlock()
if t.stopped {
return
}
t.tt.Stop()
t.tt = time.NewTicker(d)
t.unleak <- struct{}{}
go func() {
for {
select {
case now := <-t.tt.C:
t.C <- now
case <-t.unleak:
return
case <-t.stop:
return
}
}
}()
}I can see that some people have asked for it: https://stackoverflow.com/questions/36689774/dynamically-change-ticker-interval
pjebs