How to repeat for loop after one is finished?

i have function main

func main() {
	response, err := http.Get(geturl)
	if err != nil {
		fmt.Print(err.Error())
		os.Exit(1)
	}

	responseData, err := ioutil.ReadAll(response.Body)
	if err != nil {
		log.Fatal(err)
	}

	values := gjson.Get(string(responseData), "items")

	rl := ratelimit.New(3)

	prev := time.Now()

	values.ForEach(func(_, v gjson.Result) bool {
		now := rl.Take()
		url := v.Get("url").String()
		resp, err := http.Post(url, "application/x-www-form-urlencoded", nil)
		.......
		.........
		............

		return true
	})

	defer time.AfterFunc(3*time.Second, main())
}

Calling function main after timeout not working…
But at all is it right solution to repeat the for loop for new result from geturl?
And why the main() not called after timeout?

also can i improve the perfomance of the foreach loop with goroutines? does goroutines helpful here in this case?

I suspect what’s happening here is:

  • main returns.
  • mains deferred functions are run.
  • Another goroutine is scheduled to wait 3 seconds and restart main.
  • The original call to main completes, ending the program, ignorning any other goroutines, sleeping or not.

It looks to me like you want this to run forever and sleep 3 seconds between iterations. Is that true? If so, why not put the whole thing in a for { … } loop and put a call to time.Sleep at the bottom? to wait before the loop starts again? Using defer like this might make the call stack grow a function or two in depth and ultimately run out of stack space. The for loop won’t have that problem.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.