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