github.com/Axway/agent-sdk@v1.1.101/pkg/jobs/backoff.go (about)

     1  package jobs
     2  
     3  import (
     4  	"sync"
     5  	"time"
     6  )
     7  
     8  func newBackoffTimeout(startingTimeout time.Duration, maxTimeout time.Duration, increaseFactor int) *backoff {
     9  	return &backoff{
    10  		base:         startingTimeout,
    11  		max:          maxTimeout,
    12  		current:      startingTimeout,
    13  		factor:       increaseFactor,
    14  		backoffMutex: &sync.Mutex{},
    15  	}
    16  }
    17  
    18  type backoff struct {
    19  	base         time.Duration
    20  	max          time.Duration
    21  	current      time.Duration
    22  	factor       int
    23  	backoffMutex *sync.Mutex
    24  }
    25  
    26  func (b *backoff) increaseTimeout() {
    27  	b.backoffMutex.Lock()
    28  	defer b.backoffMutex.Unlock()
    29  	b.current = b.current * time.Duration(b.factor)
    30  	if b.current > b.max {
    31  		b.current = b.base // reset to base timeout
    32  	}
    33  }
    34  
    35  func (b *backoff) reset() {
    36  	b.backoffMutex.Lock()
    37  	defer b.backoffMutex.Unlock()
    38  	b.current = b.base
    39  }
    40  
    41  func (b *backoff) sleep() {
    42  	time.Sleep(b.current)
    43  }
    44  
    45  func (b *backoff) getCurrentTimeout() time.Duration {
    46  	b.backoffMutex.Lock()
    47  	defer b.backoffMutex.Unlock()
    48  	return b.current
    49  }