github.com/insolar/vanilla@v0.0.0-20201023172447-248fdf805322/chaser/chasing_delay.go (about)

     1  // Copyright 2020 Insolar Network Ltd.
     2  // All rights reserved.
     3  // This material is licensed under the Insolar License version 1.0,
     4  // available at https://github.com/insolar/assured-ledger/blob/master/LICENSE.md.
     5  
     6  package chaser
     7  
     8  import "time"
     9  
    10  func NewChasingTimer(chasingDelay time.Duration) ChasingTimer {
    11  	return ChasingTimer{chasingDelay: chasingDelay}
    12  }
    13  
    14  type ChasingTimer struct {
    15  	chasingDelay time.Duration
    16  	timer        *time.Timer
    17  	wasCleared   bool
    18  }
    19  
    20  func (c *ChasingTimer) IsEnabled() bool {
    21  	return c.chasingDelay > 0
    22  }
    23  
    24  func (c *ChasingTimer) WasStarted() bool {
    25  	return c.timer != nil
    26  }
    27  
    28  func (c *ChasingTimer) RestartChase() {
    29  
    30  	if c.chasingDelay <= 0 {
    31  		return
    32  	}
    33  
    34  	if c.timer == nil {
    35  		c.timer = time.NewTimer(c.chasingDelay)
    36  		return
    37  	}
    38  
    39  	// Restart chasing timer from this moment
    40  	if !c.wasCleared && !c.timer.Stop() {
    41  		<-c.timer.C
    42  	}
    43  	c.wasCleared = false
    44  	c.timer.Reset(c.chasingDelay)
    45  }
    46  
    47  func (c *ChasingTimer) Channel() <-chan time.Time {
    48  	if c.timer == nil {
    49  		return nil // receiver will wait indefinitely
    50  	}
    51  	return c.timer.C
    52  }
    53  
    54  func (c *ChasingTimer) ClearExpired() {
    55  	c.wasCleared = true
    56  }