start server in New call
Vladimir Bauer
9 years ago
| 26 | 26 | // Bars []*Bar |
| 27 | 27 | |
| 28 | 28 | // RefreshInterval in the time duration to wait for refreshing the output |
| 29 | RefreshInterval time.Duration | |
| 29 | // RefreshInterval time.Duration | |
| 30 | 30 | |
| 31 | lw *uilive.Writer | |
| 32 | stopChan chan struct{} | |
| 31 | lw *uilive.Writer | |
| 32 | // stopChan chan struct{} | |
| 33 | 33 | // mtx *sync.RWMutex |
| 34 | 34 | bars chan Bar |
| 35 | 35 | ticker *time.Ticker |
| 37 | 37 | |
| 38 | 38 | // New returns a new progress bar with defaults |
| 39 | 39 | func New() *Progress { |
| 40 | return &Progress{ | |
| 41 | Width: Width, | |
| 42 | Out: Out, | |
| 43 | RefreshInterval: RefreshInterval, | |
| 40 | p := &Progress{ | |
| 41 | Width: Width, | |
| 42 | Out: Out, | |
| 43 | // RefreshInterval: RefreshInterval, | |
| 44 | 44 | |
| 45 | lw: uilive.New(), | |
| 46 | stopChan: make(chan struct{}), | |
| 47 | bars: make(chan Bar), | |
| 45 | lw: uilive.New(), | |
| 46 | // stopChan: make(chan struct{}), | |
| 47 | bars: make(chan Bar), | |
| 48 | ticker: time.NewTicker(RefreshInterval), | |
| 48 | 49 | } |
| 50 | go p.server() | |
| 51 | return p | |
| 49 | 52 | } |
| 50 | 53 | |
| 51 | 54 | // Listen listens for updates and renders the progress bars |
| 52 | func (p *Progress) Listen() { | |
| 55 | func (p *Progress) server() { | |
| 53 | 56 | bars := make([]Bar, 0) |
| 54 | 57 | p.lw.Out = p.Out |
| 55 | 58 | loop: |
| 56 | 59 | for { |
| 57 | 60 | select { |
| 58 | case <-p.stopChan: // interrupt | |
| 59 | return | |
| 60 | 61 | case bar, ok := <-p.bars: |
| 61 | 62 | if !ok { |
| 62 | 63 | break loop |
| 63 | 64 | } |
| 64 | 65 | bars = append(bars, bar) |
| 65 | default: | |
| 66 | time.Sleep(p.RefreshInterval) | |
| 67 | p.mtx.RLock() | |
| 68 | for _, bar := range p.Bars { | |
| 66 | case <-p.ticker.C: | |
| 67 | for _, bar := range bars { | |
| 69 | 68 | fmt.Fprintln(p.lw, bar.String()) |
| 70 | 69 | } |
| 71 | 70 | p.lw.Flush() |
| 72 | p.mtx.RUnlock() | |
| 73 | 71 | } |
| 74 | 72 | } |
| 75 | 73 | } |