Spawning multiple jobs in a loop #265
-
Hey guys, Thanks for the awesome project! Just some background - I'm a bit of a newbie when it comes to goroutines, channels and all that magic. So bare with me here. My end goal is to spawn multiple jobs based on an array (doesn't matter - strings, int's etc):
This gives me output
So it seems that only the last of the loop is actually passed to the scheduler. Any advice here? Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Hi @ottramst glad you are enjoying the project! And we were all there once (as newbies)! 😁 This one is definitely sneaky and has to do with how the range values work in Go. Because you're passing in a function copy iteratorpackage main
import (
"fmt"
"log"
"time"
"github.com/go-co-op/gocron"
)
func main() {
a := []int{1, 2, 3}
s := gocron.NewScheduler(time.UTC)
for _, i := range a {
j := i
_, err := s.Every("1s").Do(func() { fmt.Println(j) })
if err != nil {
log.Fatalln(err)
}
}
s.StartBlocking()
} as func parampackage main
import (
"fmt"
"log"
"time"
"github.com/go-co-op/gocron"
)
func main() {
a := []int{1, 2, 3}
s := gocron.NewScheduler(time.UTC)
for _, i := range a {
_, err := s.Every("1s").Do(func(j int) { fmt.Println(j) }, i)
if err != nil {
log.Fatalln(err)
}
}
s.StartBlocking()
} |
Beta Was this translation helpful? Give feedback.
-
Thank you for this simple explanation! |
Beta Was this translation helpful? Give feedback.
Hi @ottramst glad you are enjoying the project! And we were all there once (as newbies)! 😁
This one is definitely sneaky and has to do with how the range values work in Go. Because you're passing in a function
func() { fmt.Println(i) }
the value ofi
isn't resolved immediately and when it is the value is 3, the final value in your loop. You can make it work the way you are desiring by copying the iterator value or passing it as a parameter to your function:copy iterator