Random Doubt and Periodic Activities in Golang

Asked

Viewed 84 times

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 alone arrCities[r.Int64()]

  • 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

  • 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

  • Oops, now I’ve seen the wrong Println! Hehehehe thank you!

2 answers

2

See if this example I made can help.

https://play.golang.org/p/pVlOFcmCnhO

I left a Sleep just so the program doesn’t run endlessly, but Voce can use something like the fmt.Scanln() to wait until some key is pressed or simply create some rule that leaves the systems running until something happens.

I hope I’ve helped.

2

When you use:

go func() {
        for true {
            fmt.Printf(choosenCity)
            time.Sleep(5 * time.Second)
        }
    }()
    // wait for 10 seconds before app finished
    time.Sleep(60 * time.Second)

}

You’re just printing the string choosenCity. I mean, it’s like doing: var choosenCity = "algum coisa" out of the loop. For this reason: "it always results in the same value".


You can just do:

go func() {
    for range time.Tick(1 * time.Second) {
            fmt.Println(arrCities[rand.Intn(len(cities))])
    }
}()

package main

import (
    "crypto/rand"
    "fmt"
    "math/big"
    "time"
)

var arrCities = []string{"Teste1", "Teste2", "Teste3", "Teste4", "Teste5", "Teste6"}

func main() {
    go func() {
        for range time.Tick(1 * time.Second) {
            l := big.NewInt(int64(len(arrCities)))
            if r, err := rand.Int(rand.Reader, l); err == nil {
                fmt.Println(arrCities[r.Int64()])
            }
        }
    }()

    select {} // Impede o fechamento.
}

https://play.golang.org/p/K2MV4HmQrHq

  • Very good, perfect. Small, local, versatile and functional. A question: If I wanted instead of printing with Println, it would just return me the random value, how should I do? I believe that it cannot be performed in go func(), I should probably export to a function before main() and then call it where I want to use the answer, right?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.