launchpad.net/~rogpeppe/juju-core/500-errgo-fix@v0.0.0-20140213181702-000000002356/worker/resumer/resumer.go (about)

     1  // Copyright 2012, 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package resumer
     5  
     6  import (
     7  	"fmt"
     8  	"launchpad.net/tomb"
     9  	"time"
    10  
    11  	"launchpad.net/juju-core/log"
    12  )
    13  
    14  // defaultInterval is the standard value for the interval setting.
    15  const defaultInterval = time.Minute
    16  
    17  // interval sets how often the resuming is called.
    18  var interval = defaultInterval
    19  
    20  // TransactionResumer defines the interface for types capable to
    21  // resume transactions.
    22  type TransactionResumer interface {
    23  	// ResumeTransactions resumes all pending transactions.
    24  	ResumeTransactions() error
    25  }
    26  
    27  // Resumer is responsible for a periodical resuming of pending transactions.
    28  type Resumer struct {
    29  	tomb tomb.Tomb
    30  	tr   TransactionResumer
    31  }
    32  
    33  // NewResumer periodically resumes pending transactions.
    34  func NewResumer(tr TransactionResumer) *Resumer {
    35  	rr := &Resumer{tr: tr}
    36  	go func() {
    37  		defer rr.tomb.Done()
    38  		rr.tomb.Kill(rr.loop())
    39  	}()
    40  	return rr
    41  }
    42  
    43  func (rr *Resumer) String() string {
    44  	return fmt.Sprintf("resumer")
    45  }
    46  
    47  func (rr *Resumer) Kill() {
    48  	rr.tomb.Kill(nil)
    49  }
    50  
    51  func (rr *Resumer) Stop() error {
    52  	rr.tomb.Kill(nil)
    53  	return rr.tomb.Wait()
    54  }
    55  
    56  func (rr *Resumer) Wait() error {
    57  	return rr.tomb.Wait()
    58  }
    59  
    60  func (rr *Resumer) loop() error {
    61  	for {
    62  		select {
    63  		case <-rr.tomb.Dying():
    64  			return tomb.ErrDying
    65  		case <-time.After(interval):
    66  			if err := rr.tr.ResumeTransactions(); err != nil {
    67  				log.Errorf("worker/resumer: cannot resume transactions: %v", err)
    68  			}
    69  		}
    70  	}
    71  }