T
T
Toster_someone2021-09-18 19:16:06
go
Toster_someone, 2021-09-18 19:16:06

How to set a delay during the execution of goroutines?

Hello, the question arose of how to limit the "speed of execution of goroutines", I understand that this contradicts the meaning of goroutines, but such a need arose.

Suppose I want to send several api requests to VK, and get a response for processing. But when using goroutines, I don't know how it is possible not to break the limit of 3 requests per second.

Below is the code of what I want to get as a result

for i := 0; i < 5; i++ {
    go func() {
      req := vk.WallPost(/* params */)
      resp := <-req
      fmt.Println(resp.StatusCode)
    }()
  }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Andrey Tsvetkov, 2021-09-18
@yellow79

For such purposes there is https://pkg.go.dev/golang.org/x/time/rate

D
Developer, 2021-09-18
@samodum

Send requests only when the time from the previous request is more than 1/3 sec

A
Alexandre, 2021-09-22
@Alexandre

I had a similar task with the Yandex API, I did not use goroutines, and set the delay using time.Sleep(). There was a limit of 30 requests per minute - that's 1 request in 2 seconds. So I set the delay to 2 seconds.
Using goroutines is justified when you want to get information from several sources at once. Or one goroutine receives information and gives it to another goroutine for processing ... Then in this case you cannot use time.Sleep(), since this is a blocking operation. Need to use contexts or timers

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question