github.com/songzhibin97/go-baseutils@v0.0.2-0.20240302024150-487d8ce9c082/app/bcache/sentinel.go (about)

     1  package bcache
     2  
     3  import (
     4  	"context"
     5  	"time"
     6  )
     7  
     8  // sentinel 哨兵
     9  type sentinel struct {
    10  	// interval 间隔时间 0 不开启哨兵
    11  	interval time.Duration
    12  	// ctx context
    13  	ctx context.Context
    14  	// fn 哨兵周期执行的函数
    15  	fn func()
    16  }
    17  
    18  func (s *sentinel) Start() {
    19  	if s.interval <= 0 {
    20  		return
    21  	}
    22  	tick := time.NewTicker(s.interval)
    23  	defer tick.Stop()
    24  	for {
    25  		select {
    26  		case <-tick.C:
    27  			s.fn()
    28  		case <-s.ctx.Done():
    29  			return
    30  		}
    31  	}
    32  }
    33  
    34  func NewSentinel(ctx context.Context, interval time.Duration, fn func()) *sentinel {
    35  	return &sentinel{
    36  		interval: interval,
    37  		ctx:      ctx,
    38  		fn:       fn,
    39  	}
    40  }