Reputation: 53
Is there a way to reset the *Scanner (from bufio.NewScanner) or clear old tokens? Unfortunately "func (b *Reader) Reset(r io.Reader)" does not work with *Scanner.
Update/clarification: I want to resume with the newest data from os.Stdout when "time.Sleep(30 * time.Second)" ends and skip all data that could be read during that 30 seconds.
I am currently using a for loop as dirty workaround:
scanner := bufio.NewScanner(os.Stdout)
for scanner.Scan() {
fmt.Println(scanner.Text())
if scanner.Text() == "abc" {
//do something that takes a little time
time.Sleep(30 * time.Second)
// my dirty workaround:
// skips all old tokens/inputs
for skip := time.Now(); time.Since(skip).Seconds() < 10; {
scanner.Scan()
}
}
}
Upvotes: 1
Views: 1413
Reputation:
Run the long operation in a goroutine. Discard input while the goroutine is running.
scanner := bufio.NewScanner(os.Stdout)
var discard int32
var wg sync.WaitGroup
for scanner.Scan() {
if atomic.LoadInt32(&discard) != 0 {
continue
}
fmt.Println(scanner.Text())
if scanner.Text() == "abc" {
atomic.StoreInt32(&discard, 1)
wg.Add(1)
go func() {
defer wg.Done()
defer atomic.StoreInt32(&discard, 0)
//do something that takes a little time
time.Sleep(30 * time.Second)
}()
}
}
wg.Wait() // wait for long process after EOF or error.
Upvotes: 3