Skip to content

Spawning multiple jobs in a loop #265

Answered by JohnRoesler
ottramst asked this question in Q&A
Discussion options

You must be logged in to vote

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 of i 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

package 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() { 

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Answer selected by ottramst
Comment options

You must be logged in to vote
1 reply
@JohnRoesler
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants