suppress example: resume on event
Vladimir Bauer
6 years ago
| 0 | 0 | package main |
| 1 | 1 | |
| 2 | 2 | import ( |
| 3 | "errors" | |
| 3 | 4 | "fmt" |
| 4 | 5 | "io" |
| 5 | 6 | "math/rand" |
| 14 | 15 | |
| 15 | 16 | total := 100 |
| 16 | 17 | msgCh := make(chan string) |
| 17 | filler, nextCh := makeCustomFiller(15, msgCh) | |
| 18 | resumeCh := make(chan struct{}) | |
| 19 | filler, nextCh := makeCustomFiller(msgCh, resumeCh) | |
| 18 | 20 | bar := p.Add(int64(total), filler, |
| 19 | 21 | mpb.PrependDecorators( |
| 20 | 22 | decor.Name("my bar:"), |
| 27 | 29 | go func() { |
| 28 | 30 | rng := rand.New(rand.NewSource(time.Now().UnixNano())) |
| 29 | 31 | max := 100 * time.Millisecond |
| 32 | var err error | |
| 30 | 33 | for i := 0; i < total; i++ { |
| 31 | time.Sleep(time.Duration(rng.Intn(10)+1) * max / 10) | |
| 34 | if err != nil { | |
| 35 | time.Sleep(3 * time.Second) | |
| 36 | resumeCh <- struct{}{} | |
| 37 | err = nil | |
| 38 | } else { | |
| 39 | time.Sleep(time.Duration(rng.Intn(10)+1) * max / 10) | |
| 40 | } | |
| 32 | 41 | if i == 33 { |
| 33 | msgCh <- "some error, retrying..." | |
| 42 | err = errors.New("some error") | |
| 43 | msgCh <- fmt.Sprintf("%s retrying...", err.Error()) | |
| 34 | 44 | } |
| 35 | 45 | bar.Increment() |
| 36 | 46 | } |
| 39 | 49 | p.Wait() |
| 40 | 50 | } |
| 41 | 51 | |
| 42 | func makeCustomFiller(maxFlash int, ch <-chan string) (mpb.FillerFunc, <-chan struct{}) { | |
| 52 | func makeCustomFiller(ch <-chan string, resume <-chan struct{}) (mpb.FillerFunc, <-chan struct{}) { | |
| 43 | 53 | type refiller interface { |
| 44 | 54 | SetRefill(int64) |
| 45 | 55 | } |
| 46 | 56 | filler := mpb.NewBarFiller() |
| 47 | 57 | nextCh := make(chan struct{}, 1) |
| 48 | var msg string | |
| 49 | var count int | |
| 58 | var msg *string | |
| 50 | 59 | return func(w io.Writer, width int, st *decor.Statistics) { |
| 51 | if count != 0 { | |
| 52 | nextCh <- struct{}{} | |
| 53 | limitFmt := fmt.Sprintf("%%.%ds", width) | |
| 54 | fmt.Fprintf(w, limitFmt, msg) | |
| 55 | count-- | |
| 56 | return | |
| 57 | } | |
| 58 | 60 | select { |
| 59 | case msg = <-ch: | |
| 60 | nextCh <- struct{}{} | |
| 61 | case m := <-ch: | |
| 61 | 62 | if f, ok := filler.(refiller); ok { |
| 62 | 63 | defer f.SetRefill(st.Current) |
| 63 | 64 | } |
| 64 | count = maxFlash | |
| 65 | defer func() { | |
| 66 | msg = &m | |
| 67 | }() | |
| 68 | nextCh <- struct{}{} | |
| 69 | case <-resume: | |
| 70 | msg = nil | |
| 65 | 71 | default: |
| 66 | 72 | } |
| 67 | filler.Fill(w, width, st) | |
| 73 | if msg != nil { | |
| 74 | limitFmt := fmt.Sprintf("%%.%ds", width) | |
| 75 | fmt.Fprintf(w, limitFmt, *msg) | |
| 76 | nextCh <- struct{}{} | |
| 77 | } else { | |
| 78 | filler.Fill(w, width, st) | |
| 79 | } | |
| 68 | 80 | }, nextCh |
| 69 | 81 | } |
| 70 | 82 | |