Complex example
Vladimir Bauer
8 years ago
| 0 | package main | |
| 1 | ||
| 2 | import ( | |
| 3 | "fmt" | |
| 4 | "math/rand" | |
| 5 | "sync" | |
| 6 | "time" | |
| 7 | ||
| 8 | "github.com/vbauerster/mpb" | |
| 9 | "github.com/vbauerster/mpb/decor" | |
| 10 | ) | |
| 11 | ||
| 12 | func init() { | |
| 13 | rand.Seed(time.Now().UnixNano()) | |
| 14 | } | |
| 15 | ||
| 16 | func main() { | |
| 17 | p := mpb.New() | |
| 18 | total := 200 | |
| 19 | numBars := 3 | |
| 20 | ||
| 21 | var bars []*mpb.Bar | |
| 22 | var downloadGroup []*sync.WaitGroup | |
| 23 | for i := 0; i < numBars; i++ { | |
| 24 | wg := new(sync.WaitGroup) | |
| 25 | wg.Add(1) | |
| 26 | downloadGroup = append(downloadGroup, wg) | |
| 27 | task := fmt.Sprintf("Task#%02d:", i) | |
| 28 | job := "downloading" | |
| 29 | b := p.AddBar(int64(total), mpb.BarRemoveOnComplete(), | |
| 30 | mpb.PrependDecorators( | |
| 31 | decor.StaticName(task, len(task)+1, decor.DidentRight), | |
| 32 | decor.StaticName(job, 0, decor.DwidthSync), | |
| 33 | decor.CountersNoUnit("%d / %d", 0, decor.DSyncSpace), | |
| 34 | ), | |
| 35 | mpb.AppendDecorators(decor.Percentage(5, 0)), | |
| 36 | ) | |
| 37 | go newTask(wg, b, i+1) | |
| 38 | bars = append(bars, b) | |
| 39 | } | |
| 40 | ||
| 41 | var installGroup []*sync.WaitGroup | |
| 42 | for i := 0; i < numBars; i++ { | |
| 43 | wg := new(sync.WaitGroup) | |
| 44 | wg.Add(1) | |
| 45 | installGroup = append(installGroup, wg) | |
| 46 | i := i | |
| 47 | go func() { | |
| 48 | task := fmt.Sprintf("Task#%02d:", i) | |
| 49 | job := "installing" | |
| 50 | // preparing delayed bars | |
| 51 | b := p.AddBar(int64(total), mpb.BarReplaceOnComplete(bars[i]), mpb.BarClearOnComplete(), | |
| 52 | mpb.PrependDecorators( | |
| 53 | decor.StaticName(task, len(task)+1, decor.DidentRight), | |
| 54 | decor.OnComplete(decor.StaticName(job, 0, decor.DwidthSync), "done!", 0, decor.DwidthSync), | |
| 55 | decor.OnComplete(decor.ETA(0, decor.DSyncSpace), "", 0, decor.DSyncSpace), | |
| 56 | ), | |
| 57 | mpb.AppendDecorators( | |
| 58 | decor.OnComplete(decor.Percentage(5, 0), "", 0, 0), | |
| 59 | ), | |
| 60 | ) | |
| 61 | // waiting for download to complete, before starting install job | |
| 62 | downloadGroup[i].Wait() | |
| 63 | go newTask(wg, b, numBars-i) | |
| 64 | }() | |
| 65 | } | |
| 66 | ||
| 67 | // this wait loop may be skipped, but not recommended | |
| 68 | for _, wg := range installGroup { | |
| 69 | wg.Wait() | |
| 70 | } | |
| 71 | ||
| 72 | p.Wait() | |
| 73 | } | |
| 74 | ||
| 75 | func newTask(wg *sync.WaitGroup, b *mpb.Bar, incrBy int) { | |
| 76 | defer wg.Done() | |
| 77 | max := 100 * time.Millisecond | |
| 78 | for !b.Completed() { | |
| 79 | time.Sleep(time.Duration(rand.Intn(10)+1) * max / 10) | |
| 80 | b.IncrBy(incrBy) | |
| 81 | } | |
| 82 | } |