I am noob in golang, but I would like to change a source code that writes data into database every minute to every second. I have trobles to find what Tick does in the code. The config.SampleRate is integer = 1, which means every minute = every 60 seconds
What this tick is all about and the end part of it: <-tick, combined with counter i?
i := 0
tick := time.Tick(time.Duration(1000/config.Samplerate) * time.Millisecond)
for {
// Restart the accumulator loop every 60 seconds.
if i > (60*config.Samplerate - 1) {
i = 0
//some code here
}
//some code there
}
<-tick
i++
tick
is a channel in Go. If you look at the docs, tick
should send something to the channel once each time interval, which is specified by time.Duration(1000/config.Samplerate) * time.Millisecond
in your code. <-tick
just waits for that time interval to pass.
i
keeps track of how many seconds pass, so every time it ticks, you add one to i
. The if statement checks when one minute passes.
So, the code inside the if statement fires every 60 seconds, while the code right under the if block fires every second.