github.com/cloud-green/juju@v0.0.0-20151002100041-a00291338d3d/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 "time" 9 10 "github.com/juju/loggo" 11 "launchpad.net/tomb" 12 ) 13 14 var logger = loggo.GetLogger("juju.worker.resumer") 15 16 // defaultInterval is the standard value for the interval setting. 17 const defaultInterval = time.Minute 18 19 // interval sets how often the resuming is called. 20 var interval = defaultInterval 21 22 // TransactionResumer defines the interface for types capable to 23 // resume transactions. 24 type TransactionResumer interface { 25 // ResumeTransactions resumes all pending transactions. 26 ResumeTransactions() error 27 } 28 29 // Resumer is responsible for a periodical resuming of pending transactions. 30 type Resumer struct { 31 tomb tomb.Tomb 32 tr TransactionResumer 33 } 34 35 // NewResumer periodically resumes pending transactions. 36 func NewResumer(tr TransactionResumer) *Resumer { 37 rr := &Resumer{tr: tr} 38 go func() { 39 defer rr.tomb.Done() 40 rr.tomb.Kill(rr.loop()) 41 }() 42 return rr 43 } 44 45 func (rr *Resumer) String() string { 46 return fmt.Sprintf("resumer") 47 } 48 49 func (rr *Resumer) Kill() { 50 rr.tomb.Kill(nil) 51 } 52 53 func (rr *Resumer) Stop() error { 54 rr.tomb.Kill(nil) 55 return rr.tomb.Wait() 56 } 57 58 func (rr *Resumer) Wait() error { 59 return rr.tomb.Wait() 60 } 61 62 func (rr *Resumer) loop() error { 63 for { 64 select { 65 case <-rr.tomb.Dying(): 66 return tomb.ErrDying 67 case <-time.After(interval): 68 if err := rr.tr.ResumeTransactions(); err != nil { 69 logger.Errorf("cannot resume transactions: %v", err) 70 } 71 } 72 } 73 }