sort example
Vladimir Bauer
9 years ago
| 0 | package main | |
| 1 | ||
| 2 | import ( | |
| 3 | "fmt" | |
| 4 | "math/rand" | |
| 5 | "time" | |
| 6 | ||
| 7 | "github.com/vbauerster/mpb" | |
| 8 | ) | |
| 9 | ||
| 10 | const ( | |
| 11 | maxBlockSize = 12 | |
| 12 | ) | |
| 13 | ||
| 14 | func main() { | |
| 15 | ||
| 16 | p := mpb.New().RefreshRate(80 * time.Millisecond).Sort(mpb.SortTop).SetWidth(60) | |
| 17 | ||
| 18 | bar1 := p.AddBar(100).AppendETA().PrependFunc(getDecor("Bar#1")) | |
| 19 | go func() { | |
| 20 | blockSize := rand.Intn(maxBlockSize) + 1 | |
| 21 | for i := 0; i < 100; i++ { | |
| 22 | time.Sleep(time.Duration(blockSize) * (50*time.Millisecond + time.Duration(rand.Intn(5*int(time.Millisecond))))) | |
| 23 | bar1.Incr(1) | |
| 24 | blockSize = rand.Intn(maxBlockSize) + 1 | |
| 25 | } | |
| 26 | }() | |
| 27 | ||
| 28 | bar2 := p.AddBar(60).AppendETA().PrependFunc(getDecor("Bar#2")) | |
| 29 | go func() { | |
| 30 | blockSize := rand.Intn(maxBlockSize) + 1 | |
| 31 | for i := 0; i < 60; i++ { | |
| 32 | time.Sleep(time.Duration(blockSize) * (50*time.Millisecond + time.Duration(rand.Intn(5*int(time.Millisecond))))) | |
| 33 | bar2.Incr(1) | |
| 34 | blockSize = rand.Intn(maxBlockSize) + 1 | |
| 35 | } | |
| 36 | }() | |
| 37 | ||
| 38 | bar3 := p.AddBar(80).AppendETA().PrependFunc(getDecor("Bar#3")) | |
| 39 | go func() { | |
| 40 | blockSize := rand.Intn(maxBlockSize) + 1 | |
| 41 | for i := 0; i < 80; i++ { | |
| 42 | time.Sleep(time.Duration(blockSize) * (50*time.Millisecond + time.Duration(rand.Intn(5*int(time.Millisecond))))) | |
| 43 | bar3.Incr(1) | |
| 44 | blockSize = rand.Intn(maxBlockSize) + 1 | |
| 45 | } | |
| 46 | }() | |
| 47 | ||
| 48 | // time.Sleep(time.Second) | |
| 49 | // p.RemoveBar(bar2) | |
| 50 | ||
| 51 | p.WaitAndStop() | |
| 52 | bar2.Incr(2) | |
| 53 | fmt.Println("stop") | |
| 54 | // p.AddBar(1) // panic: send on closed channnel | |
| 55 | } | |
| 56 | ||
| 57 | func getDecor(name string) mpb.DecoratorFunc { | |
| 58 | return func(s *mpb.Statistics) string { | |
| 59 | str := fmt.Sprintf("%d/%d", s.Completed, s.Total) | |
| 60 | return fmt.Sprintf("%s %-7s", name, str) | |
| 61 | } | |
| 62 | } |