github.com/TeaOSLab/EdgeNode@v1.3.8/internal/utils/ticker.go (about)

     1  package utils
     2  
     3  import (
     4  	"github.com/TeaOSLab/EdgeNode/internal/zero"
     5  	"sync"
     6  	"time"
     7  )
     8  
     9  // Ticker 类似于time.Ticker,但能够真正地停止
    10  type Ticker struct {
    11  	raw  *time.Ticker
    12  	done chan zero.Zero
    13  	once sync.Once
    14  
    15  	C <-chan time.Time
    16  }
    17  
    18  // NewTicker 创建新Ticker
    19  func NewTicker(duration time.Duration) *Ticker {
    20  	raw := time.NewTicker(duration)
    21  	return &Ticker{
    22  		raw:  raw,
    23  		C:    raw.C,
    24  		done: make(chan zero.Zero, 1),
    25  	}
    26  }
    27  
    28  // Next 查找下一个Tick
    29  func (this *Ticker) Next() bool {
    30  	select {
    31  	case <-this.raw.C:
    32  		return true
    33  	case <-this.done:
    34  		return false
    35  	}
    36  }
    37  
    38  // Stop 停止
    39  func (this *Ticker) Stop() {
    40  	this.once.Do(func() {
    41  		this.raw.Stop()
    42  		this.done <- zero.New()
    43  	})
    44  }