github.com/makyo/juju@v0.0.0-20160425123129-2608902037e9/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 "launchpad.net/tomb"
     7  
     8  // simpleWorker implements the worker returned by NewSimpleWorker.
     9  type simpleWorker struct {
    10  	tomb tomb.Tomb
    11  }
    12  
    13  // NewSimpleWorker returns a worker that runs the given function.  The
    14  // stopCh argument will be closed when the worker is killed. The error returned
    15  // by the doWork function will be returned by the worker's Wait function.
    16  func NewSimpleWorker(doWork func(stopCh <-chan struct{}) error) Worker {
    17  	w := &simpleWorker{}
    18  	go func() {
    19  		defer w.tomb.Done()
    20  		w.tomb.Kill(doWork(w.tomb.Dying()))
    21  	}()
    22  	return w
    23  }
    24  
    25  // Kill implements Worker.Kill() and will close the channel given to the doWork
    26  // function.
    27  func (w *simpleWorker) Kill() {
    28  	w.tomb.Kill(nil)
    29  }
    30  
    31  // Wait implements Worker.Wait(), and will return the error returned by
    32  // the doWork function.
    33  func (w *simpleWorker) Wait() error {
    34  	return w.tomb.Wait()
    35  }