github.com/lingyao2333/mo-zero@v1.4.1/core/executors/lessexecutor.go (about)

     1  package executors
     2  
     3  import (
     4  	"time"
     5  
     6  	"github.com/lingyao2333/mo-zero/core/syncx"
     7  	"github.com/lingyao2333/mo-zero/core/timex"
     8  )
     9  
    10  // A LessExecutor is an executor to limit execution once within given time interval.
    11  type LessExecutor struct {
    12  	threshold time.Duration
    13  	lastTime  *syncx.AtomicDuration
    14  }
    15  
    16  // NewLessExecutor returns a LessExecutor with given threshold as time interval.
    17  func NewLessExecutor(threshold time.Duration) *LessExecutor {
    18  	return &LessExecutor{
    19  		threshold: threshold,
    20  		lastTime:  syncx.NewAtomicDuration(),
    21  	}
    22  }
    23  
    24  // DoOrDiscard executes or discards the task depends on if
    25  // another task was executed within the time interval.
    26  func (le *LessExecutor) DoOrDiscard(execute func()) bool {
    27  	now := timex.Now()
    28  	lastTime := le.lastTime.Load()
    29  	if lastTime == 0 || lastTime+le.threshold < now {
    30  		le.lastTime.Set(now)
    31  		execute()
    32  		return true
    33  	}
    34  
    35  	return false
    36  }