-
Notifications
You must be signed in to change notification settings - Fork 12
/
progress.go
50 lines (44 loc) · 1 KB
/
progress.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package main
import (
"fmt"
"io"
"time"
)
// ProgressPrinter periodically prints until it is stopped.
type ProgressPrinter struct {
out io.Writer
stop chan struct{}
stopped chan struct{}
}
// NewProgressPrinter returns a new ProgressPrinter.
func NewProgressPrinter(out io.Writer) *ProgressPrinter {
return &ProgressPrinter{
out: out,
stop: make(chan struct{}),
stopped: make(chan struct{}),
}
}
// Start starts the printer, and immediately returns.
func (pp *ProgressPrinter) Start() {
go func() {
defer close(pp.stopped)
for {
ticker := time.NewTicker(1 * time.Second)
select {
case <-pp.stop:
fmt.Fprintln(pp.out)
return
case <-ticker.C:
fmt.Fprintf(pp.out, ".")
}
}
}()
}
// Stop stops printing to `out`. No prints will occur after `Stop` returns.
func (pp *ProgressPrinter) Stop() {
close(pp.stop)
<-pp.stopped
// Reset the channels so that the progress printer can be invoked again.
pp.stop = make(chan struct{})
pp.stopped = make(chan struct{})
}