File tree Expand file tree Collapse file tree 1 file changed +17
-16
lines changed Expand file tree Collapse file tree 1 file changed +17
-16
lines changed Original file line number Diff line number Diff line change @@ -8,38 +8,31 @@ import (
88type EventTimer struct {
99 f func ()
1010 timer * time.Timer
11- reset chan time. Duration
11+ done chan struct {}
1212 wg sync.WaitGroup
1313}
1414
1515func NewEventTimer (task func ()) * EventTimer {
1616 t := & EventTimer {
1717 f : task ,
18- reset : make (chan time.Duration , 1 ),
18+ timer : newStoppedTimer (),
19+ done : make (chan struct {}),
1920 }
2021
2122 t .wg .Add (1 )
2223 go func () {
2324 defer t .wg .Done ()
24- var c <- chan time.Time
2525
2626 for {
2727 select {
2828
29- case <- c :
29+ case <- t . timer . C :
3030 t .f ()
3131
32- case d , ok := <- t .reset :
33- if ! ok {
34- return
35- }
32+ case <- t .done :
33+ t .timer .Stop ()
34+ return
3635
37- if t .timer != nil {
38- t .timer .Reset (d )
39- } else {
40- t .timer = time .NewTimer (d )
41- c = t .timer .C
42- }
4336 }
4437 }
4538 }()
@@ -52,7 +45,7 @@ func (t *EventTimer) Stop() {
5245 return
5346 }
5447
55- close (t .reset )
48+ close (t .done )
5649 t .wg .Wait ()
5750}
5851
@@ -61,5 +54,13 @@ func (t *EventTimer) Reset(timeout time.Duration) {
6154 return
6255 }
6356
64- t .reset <- timeout
57+ t .timer .Reset (timeout )
58+ }
59+
60+ func newStoppedTimer () * time.Timer {
61+ timer := time .NewTimer (time .Second )
62+ if ! timer .Stop () {
63+ <- timer .C
64+ }
65+ return timer
6566}
You can’t perform that action at this time.
0 commit comments