github.com/makyo/juju@v0.0.0-20160425123129-2608902037e9/worker/txnpruner/txnpruner.go (about)

     1  // Copyright 2015 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package txnpruner
     5  
     6  import (
     7  	"time"
     8  
     9  	"github.com/juju/errors"
    10  
    11  	"github.com/juju/juju/worker"
    12  )
    13  
    14  // TransactionPruner defines the interface for types capable of
    15  // pruning transactions.
    16  type TransactionPruner interface {
    17  	MaybePruneTransactions() error
    18  }
    19  
    20  // New returns a worker which periodically prunes the data for
    21  // completed transactions.
    22  func New(tp TransactionPruner, interval time.Duration) worker.Worker {
    23  	return worker.NewSimpleWorker(func(stopCh <-chan struct{}) error {
    24  		// Use a timer rather than a ticker because pruning could
    25  		// sometimes take a while and we don't want pruning attempts
    26  		// to occur back-to-back.
    27  		// TODO(fwereade): 2016-03-17 lp:1558657
    28  		timer := time.NewTimer(interval)
    29  		defer timer.Stop()
    30  		for {
    31  			select {
    32  			case <-timer.C:
    33  				err := tp.MaybePruneTransactions()
    34  				if err != nil {
    35  					return errors.Annotate(err, "pruning failed, txnpruner stopping")
    36  				}
    37  				timer.Reset(interval)
    38  			case <-stopCh:
    39  				return nil
    40  			}
    41  		}
    42  	})
    43  }