poplog example
Vladimir Bauer
7 years ago
| 0 | package main | |
| 1 | ||
| 2 | import ( | |
| 3 | "fmt" | |
| 4 | "io" | |
| 5 | "math/rand" | |
| 6 | "sync" | |
| 7 | "time" | |
| 8 | ||
| 9 | "github.com/vbauerster/mpb/v4" | |
| 10 | "github.com/vbauerster/mpb/v4/decor" | |
| 11 | ) | |
| 12 | ||
| 13 | func main() { | |
| 14 | rand.Seed(time.Now().UnixNano()) | |
| 15 | p := mpb.New(mpb.PopCompletedMode()) | |
| 16 | ||
| 17 | total, numBars := 100, 2 | |
| 18 | for i := 0; i < numBars; i++ { | |
| 19 | name := fmt.Sprintf("Bar#%d:", i) | |
| 20 | bar := p.AddBar(int64(total), | |
| 21 | mpb.BarNoPop(), | |
| 22 | mpb.PrependDecorators( | |
| 23 | decor.Name(name), | |
| 24 | decor.Percentage(decor.WCSyncSpace), | |
| 25 | ), | |
| 26 | mpb.AppendDecorators( | |
| 27 | decor.OnComplete( | |
| 28 | decor.EwmaETA(decor.ET_STYLE_GO, 60), "done!", | |
| 29 | ), | |
| 30 | ), | |
| 31 | ) | |
| 32 | // simulating some work | |
| 33 | go func() { | |
| 34 | max := 100 * time.Millisecond | |
| 35 | for i := 0; i < total; i++ { | |
| 36 | start := time.Now() | |
| 37 | time.Sleep(time.Duration(rand.Intn(10)+1) * max / 10) | |
| 38 | bar.Increment(time.Since(start)) | |
| 39 | } | |
| 40 | }() | |
| 41 | } | |
| 42 | ||
| 43 | var wg sync.WaitGroup | |
| 44 | wg.Add(1) | |
| 45 | go func() { | |
| 46 | defer wg.Done() | |
| 47 | max := 3000 * time.Millisecond | |
| 48 | for i := 0; i < 10; i++ { | |
| 49 | p.Add(0, makeLogBar(fmt.Sprintf("some log: %d", i))).SetTotal(0, true) | |
| 50 | time.Sleep(time.Duration(rand.Intn(10)+1) * max / 10) | |
| 51 | } | |
| 52 | }() | |
| 53 | ||
| 54 | wg.Wait() | |
| 55 | p.Wait() | |
| 56 | } | |
| 57 | ||
| 58 | func makeLogBar(msg string) mpb.FillerFunc { | |
| 59 | return func(w io.Writer, width int, st *decor.Statistics) { | |
| 60 | fmt.Fprint(w, msg) | |
| 61 | } | |
| 62 | } |