github.com/unicornultrafoundation/go-u2u@v1.0.0-rc1.0.20240205080301-e74a83d3fadc/gossip/tflusher.go (about)

     1  package gossip
     2  
     3  import (
     4  	"sync"
     5  	"time"
     6  )
     7  
     8  type PeriodicFlusherCallaback struct {
     9  	busy         func() bool
    10  	commitNeeded func() bool
    11  	commit       func()
    12  }
    13  
    14  // PeriodicFlusher periodically commits the Store if isCommitNeeded returns true
    15  type PeriodicFlusher struct {
    16  	period   time.Duration
    17  	callback PeriodicFlusherCallaback
    18  
    19  	wg   sync.WaitGroup
    20  	quit chan struct{}
    21  }
    22  
    23  func (c *PeriodicFlusher) loop() {
    24  	defer c.wg.Done()
    25  	ticker := time.NewTicker(c.period)
    26  	defer ticker.Stop()
    27  	for {
    28  		select {
    29  		case <-ticker.C:
    30  			if !c.callback.busy() && c.callback.commitNeeded() {
    31  				c.callback.commit()
    32  			}
    33  		case <-c.quit:
    34  			return
    35  		}
    36  	}
    37  }
    38  
    39  func (c *PeriodicFlusher) Start() {
    40  	c.wg.Add(1)
    41  	go c.loop()
    42  }
    43  
    44  func (c *PeriodicFlusher) Stop() {
    45  	close(c.quit)
    46  	c.wg.Wait()
    47  }