add new ticker task convenience function

This commit is contained in:
Jesse Duffield 2019-06-02 20:30:33 +10:00
parent 28b488b740
commit 69b11cbfd2
2 changed files with 24 additions and 15 deletions

View file

@ -123,13 +123,7 @@ func (gui *Gui) renderContainerStats(mainView *gocui.View, container *commands.C
mainView.Autoscroll = false mainView.Autoscroll = false
mainView.Title = "Stats" mainView.Title = "Stats"
return gui.T.NewTask(func(stop chan struct{}) { return gui.T.NewTickerTask(time.Second, func() {
tickChan := time.NewTicker(time.Second)
for {
select {
case <-stop:
return
case <-tickChan.C:
width, _ := mainView.Size() width, _ := mainView.Size()
contents, err := container.RenderStats(width) contents, err := container.RenderStats(width)
@ -138,8 +132,6 @@ func (gui *Gui) renderContainerStats(mainView *gocui.View, container *commands.C
} }
gui.reRenderString(gui.g, "main", contents) gui.reRenderString(gui.g, "main", contents)
}
}
}) })
} }

View file

@ -2,6 +2,7 @@ package tasks
import ( import (
"sync" "sync"
"time"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
@ -53,3 +54,19 @@ func (t *Task) Stop() {
<-t.notifyStopped <-t.notifyStopped
return return
} }
// NewTickerTask is a convenience function for making a new task that repeats some action once per e.g. second
func (t *TaskManager) NewTickerTask(duration time.Duration, f func()) error {
return t.NewTask(func(stop chan struct{}) {
tickChan := time.NewTicker(time.Second)
f() // calling f first so that we're not waiting for the first tick
for {
select {
case <-stop:
return
case <-tickChan.C:
f()
}
}
})
}