github.com/XiaoMi/Gaea@v1.2.5/util/timer/randticker.go (about)

     1  /*
     2  Copyright 2017 Google Inc.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package timer
    18  
    19  import (
    20  	"math/rand"
    21  	"time"
    22  )
    23  
    24  // RandTicker is just like time.Ticker, except that
    25  // it adds randomness to the events.
    26  type RandTicker struct {
    27  	C    <-chan time.Time
    28  	done chan struct{}
    29  }
    30  
    31  // NewRandTicker creates a new RandTicker. d is the duration,
    32  // and variance specifies the variance. The ticker will tick
    33  // every d +/- variance.
    34  func NewRandTicker(d, variance time.Duration) *RandTicker {
    35  	c := make(chan time.Time, 1)
    36  	done := make(chan struct{})
    37  	go func() {
    38  		rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
    39  		for {
    40  			vr := time.Duration(rnd.Int63n(int64(2*variance)) - int64(variance))
    41  			tmr := time.NewTimer(d + vr)
    42  			select {
    43  			case <-tmr.C:
    44  				select {
    45  				case c <- time.Now():
    46  				default:
    47  				}
    48  			case <-done:
    49  				tmr.Stop()
    50  				close(c)
    51  				return
    52  			}
    53  		}
    54  	}()
    55  	return &RandTicker{
    56  		C:    c,
    57  		done: done,
    58  	}
    59  }
    60  
    61  // Stop stops the ticker and closes the underlying channel.
    62  func (tkr *RandTicker) Stop() {
    63  	close(tkr.done)
    64  }