Codebase list golang-github-vbauerster-mpb / 5b5603a
suppress example: resume on event Vladimir Bauer 6 years ago
1 changed file(s) with 29 addition(s) and 17 deletion(s). Raw diff Collapse all Expand all
00 package main
11
22 import (
3 "errors"
34 "fmt"
45 "io"
56 "math/rand"
1415
1516 total := 100
1617 msgCh := make(chan string)
17 filler, nextCh := makeCustomFiller(15, msgCh)
18 resumeCh := make(chan struct{})
19 filler, nextCh := makeCustomFiller(msgCh, resumeCh)
1820 bar := p.Add(int64(total), filler,
1921 mpb.PrependDecorators(
2022 decor.Name("my bar:"),
2729 go func() {
2830 rng := rand.New(rand.NewSource(time.Now().UnixNano()))
2931 max := 100 * time.Millisecond
32 var err error
3033 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 }
3241 if i == 33 {
33 msgCh <- "some error, retrying..."
42 err = errors.New("some error")
43 msgCh <- fmt.Sprintf("%s retrying...", err.Error())
3444 }
3545 bar.Increment()
3646 }
3949 p.Wait()
4050 }
4151
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{}) {
4353 type refiller interface {
4454 SetRefill(int64)
4555 }
4656 filler := mpb.NewBarFiller()
4757 nextCh := make(chan struct{}, 1)
48 var msg string
49 var count int
58 var msg *string
5059 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 }
5860 select {
59 case msg = <-ch:
60 nextCh <- struct{}{}
61 case m := <-ch:
6162 if f, ok := filler.(refiller); ok {
6263 defer f.SetRefill(st.Current)
6364 }
64 count = maxFlash
65 defer func() {
66 msg = &m
67 }()
68 nextCh <- struct{}{}
69 case <-resume:
70 msg = nil
6571 default:
6672 }
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 }
6880 }, nextCh
6981 }
7082