gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/timer/timer.go (about)

     1  package timer
     2  
     3  import (
     4  	"time"
     5  )
     6  
     7  type Timer struct {
     8  	timer  *time.Timer
     9  	closed bool
    10  	C      chan struct{}
    11  }
    12  
    13  func NewTimer(c chan struct{}) *Timer {
    14  	if c == nil {
    15  		c = make(chan struct{}, 1)
    16  	}
    17  	return &Timer{C: c}
    18  }
    19  
    20  func (t *Timer) retryCallback() {
    21  	t.C <- struct{}{}
    22  }
    23  
    24  func (t *Timer) Trigger() *Timer {
    25  	t.C <- struct{}{}
    26  	return t
    27  }
    28  
    29  func (t *Timer) After(duration time.Duration) *Timer {
    30  	if t.timer == nil {
    31  		t.timer = time.AfterFunc(duration, t.retryCallback)
    32  	} else {
    33  		t.timer.Reset(duration)
    34  	}
    35  	return t
    36  }
    37  
    38  func (t *Timer) Stop() bool {
    39  	if t.timer != nil {
    40  		return t.timer.Stop()
    41  	}
    42  	return false
    43  }