1
Is there any way I can get one executed fmt.Printf(choosenCity)
every 6 hours and, at each run, he chooses a different element of the Array?
I even managed to get him to perform periodically after a few gambiarras, but I read that it is not recommended to use time.sleep()
and it always results in the same value, unless I close and run the script again.
arrCities := [6]string{
"Teste1",
"Teste2",
"Teste3",
"Teste4",
"Teste5",
"Teste6",
}
rand.Seed(time.Now().UnixNano())
choosenCity := arrCities[rand.Intn(len(arrCities))]
go func() {
for true {
fmt.Printf(choosenCity)
time.Sleep(5 * time.Second)
}
}()
// wait for 10 seconds before app finished
time.Sleep(60 * time.Second)
}
//OBS a Função `go func()` está dentro da main()
I would like (without closing the script), every 6 hours, Pickar a random element of the Array, and then print.
Well, all the answers helped me in a way, I thought I could exemplify the problem with code syntax that I went through above. But in reality, what I desire is still a little different.
For more explanations:
Actually this "generator" of a random number, is to pull random data from an API. I thought with the example I gave in the post, I could do it, but I couldn’t. To explain better, here’s a snippet of code as I imagined it would work:
Choosen := fmt.Println(arrCities[r.Int64()]
URL := fmt.Sprintf("https://api.exemplo.io/data/?dado=%s", Choosen)
///... requisição e parsering da response
E então, aí, o "Ticker" que iria realizar tal atividade com a response da API.
///... requisição e parsering da response
//E AQUI VIRIA O TIMER
fmt.Println(apiResults.Data1)
//
The question is that I need Random for the API and with the API answer, then yes, the Timer to perform
fmt.Println
It won’t work, instead leave it alonearrCities[r.Int64()]
– suriyel
I don’t quite understand it yet, but if you want to take a random API data every 6h you can put all this logic inside the timer
– suriyel
I want the generator and the timer separated, you know? It is not a timer to generate a random number, it is a timer to run a function with the response of an API that the GET request going to the api uses the random number
– Dasx
Oops, now I’ve seen the wrong Println! Hehehehe thank you!
– Dasx