Skip to content

Commit

Permalink
fixed #12 app now properly cleans up.
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisMcKenzie committed Nov 11, 2015
1 parent a69d776 commit e237e96
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
6 changes: 5 additions & 1 deletion commands/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"log"
"os"
"os/signal"
"sync"

"github.com/ChrisMcKenzie/dropship/service"
"github.com/ChrisMcKenzie/dropship/work"
Expand All @@ -28,8 +29,10 @@ func agent(c *cobra.Command, args []string) {
t := work.NewRunner(len(services))
shutdownCh := make(chan struct{})

var wg sync.WaitGroup
wg.Add(len(services))
for _, s := range services {
_, err := work.NewDispatcher(s, t, shutdownCh)
_, err := work.NewDispatcher(s, t, &wg, shutdownCh)
if err != nil {
log.Fatal(err)
}
Expand All @@ -39,6 +42,7 @@ func agent(c *cobra.Command, args []string) {
signal.Notify(sigs, os.Interrupt)
<-sigs
close(shutdownCh)
wg.Wait()

t.Shutdown()
}
16 changes: 10 additions & 6 deletions work/dispatcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"log"
"os/exec"
"strings"
"sync"
"time"

"github.com/ChrisMcKenzie/dropship/hook"
Expand All @@ -23,21 +24,24 @@ type Dispatcher struct {
ticker *time.Ticker
task *Runner
hash string
duration time.Duration
wg *sync.WaitGroup
shutdownCh <-chan struct{}
}

func NewDispatcher(cfg service.Config, t *Runner, shutdownCh <-chan struct{}) (*Dispatcher, error) {
func NewDispatcher(cfg service.Config, t *Runner, wg *sync.WaitGroup, shutdownCh <-chan struct{}) (*Dispatcher, error) {
w := Dispatcher{
config: cfg,
task: t,
shutdownCh: shutdownCh,
wg: wg,
}

dur, err := time.ParseDuration(cfg.CheckInterval)
var err error
w.duration, err = time.ParseDuration(cfg.CheckInterval)
if err != nil {
return nil, err
}
w.ticker = time.NewTicker(dur)

go w.start()

Expand All @@ -47,14 +51,14 @@ func NewDispatcher(cfg service.Config, t *Runner, shutdownCh <-chan struct{}) (*
func (w *Dispatcher) start() {
for {
select {
case <-w.ticker.C:
w.task.Do(w)
case _, ok := <-w.shutdownCh:
if !ok {
log.Printf("Shutting down dispatcher for %s", w.config.Name)
w.ticker.Stop()
w.wg.Done()
return
}
case <-time.After(w.duration):
w.task.Do(w)
}
}
}
Expand Down

0 comments on commit e237e96

Please # to comment.