github.com/cloud-green/juju@v0.0.0-20151002100041-a00291338d3d/worker/simpleworker.go (about) 1 // Copyright 2014 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package worker 5 6 import ( 7 "launchpad.net/tomb" 8 ) 9 10 // simpleWorker implements the worker returned by NewSimpleWorker. 11 type simpleWorker struct { 12 tomb tomb.Tomb 13 } 14 15 // NewSimpleWorker returns a worker that runs the given function. The 16 // stopCh argument will be closed when the worker is killed. The error returned 17 // by the doWork function will be returned by the worker's Wait function. 18 func NewSimpleWorker(doWork func(stopCh <-chan struct{}) error) Worker { 19 w := &simpleWorker{} 20 go func() { 21 defer w.tomb.Done() 22 w.tomb.Kill(doWork(w.tomb.Dying())) 23 }() 24 return w 25 } 26 27 // Kill implements Worker.Kill() and will close the channel given to the doWork 28 // function. 29 func (w *simpleWorker) Kill() { 30 w.tomb.Kill(nil) 31 } 32 33 // Wait implements Worker.Wait(), and will return the error returned by 34 // the doWork function. 35 func (w *simpleWorker) Wait() error { 36 return w.tomb.Wait() 37 }