I have a function that I want to poll every 20 seconds or so right now it's called in a go routine like so:
go StartTradeBot()
then in the body of the function:
func StartTradeBot() {
for {
// All the stuff to do
time.Sleep(20 * time.Second)
}
}
Is it more efficient like this?
or should I wrap my goroutine instead like
for {
go StartTradeBot()
time.Sleep(20 * time.Second)
}
There are at least three variations on how do this, each with different functionality. Because the interval is 20 seconds, the difference in performance is negligible. Pick the variation that best meets the application's functionality requirements.
Option 1: Pause 20 seconds between each operation.
for {
// Do stuff
time.Sleep(20 * time.Second)
}
Option 2: Start an operation every 20 seconds, even if previous operation is still executing.
for {
go func() {
// Do stuff
}()
time.Sleep(20 * time.Second)
}
Option 3: Start operation every 20 seconds or after previous operation completes, whichever is later.
t := time.NewTicker(20 * time.Second)
for range t.C {
// Do stuff
}