github.com/pyroscope-io/pyroscope@v0.37.3-0.20230725203016-5f6947968bd0/pkg/util/throttle/throttle.go (about)

     1  package throttle
     2  
     3  import (
     4  	"sync"
     5  	"time"
     6  )
     7  
     8  type Throttler struct {
     9  	m        sync.Mutex
    10  	t        time.Time
    11  	Duration time.Duration
    12  	skipped  int
    13  }
    14  
    15  func New(d time.Duration) *Throttler {
    16  	return &Throttler{
    17  		Duration: d,
    18  	}
    19  }
    20  
    21  func (t *Throttler) Run(cb func(int)) {
    22  	t.m.Lock()
    23  	defer t.m.Unlock()
    24  
    25  	now := time.Now()
    26  	if t.t.IsZero() || t.t.Before(now.Add(-t.Duration)) {
    27  		cb(t.skipped)
    28  		t.skipped = 0
    29  		t.t = now
    30  	} else {
    31  		t.skipped++
    32  	}
    33  }