Golang: how to print data from running goroutine at fixed intervals?

I have problems understanding channels in the golang. As far as I know, feeds are the right way to publish data to the console at a given time interval.

So to speak, I have a goroutine that does the work, and then in my main loop, I would like to print data from this goroutine every second.

How would something like this be encoded? It would be very helpful to get a simple example.

+7
go
source share
2 answers

You may have some protected shared state in memory that you are updating from your long process. Then you have a timer that runs this general health check every second. Here is a quick example: http://play.golang.org/p/gfGvhHUWIc

the code:

package main import ( "fmt" "sync" "time" ) type Progress struct { current string rwlock sync.RWMutex } func (p *Progress) Set(value string) { p.rwlock.Lock() defer p.rwlock.Unlock() p.current = value } func (p *Progress) Get() string { p.rwlock.RLock() defer p.rwlock.RUnlock() return p.current } func longJob(progress *Progress) { i := 0 for { time.Sleep(100 * time.Millisecond) i++ progress.Set(fmt.Sprintf("Current progress message: %v", i)) } } func main() { fmt.Println("test") c := time.Tick(1 * time.Second) progress := &Progress{} go longJob(progress) for { select { case <-c: fmt.Println(progress.Get()) } } } 
+7
source share

If you want to transfer data from one routine to another, you can do it like

 package main import "fmt" func routine(output chan int) { for i := 0; i < 1000; i++ { output <- i } close(output) } func main() { ch := make(chan int) go routine(ch) for i := range ch { fmt.Printf("%d ", i) } } 

But this is not quite what you asked for, you wanted to get a routine status every second. For this channel is not a good solution. A variable shared between two routines will solve the problem. One routine updates it, another procedure reads it every second.

+1
source share

All Articles