0

I have to create a Kotlin application that needs to fetch data from a RPI by WiFi in pseudo-real time (every five seconds).

I have tried doing that using a Thread, like this :

     private fun getRecentData() {
        requestType = recentDataRequest
        binding.periodDataButton.isVisible = true
        binding.realTimeDataButton.isVisible = false

        while (true) {
            communication.requette(requestType)
            Thread.sleep(5000)
        }
    }

but it makes my app crash (I'm not really surpised by this, to be honest). I'v also tried doing a loop on the server side, like this :

while (true) {
                            //Construction trame données temps réel à envoyer au client
                            gestionBDD.prepareRequete("select * from recent_data");
                            rs = gestionBDD.executeQuerry();
                            while (rs.next()) {
                                recentData.setIntensity(rs.getFloat("intensity"));
                                recentData.setTension(rs.getFloat("tension"));
                                recentData.setApparentPower(rs.getFloat("apparent_power"));
                                recentData.setReactivePower(rs.getFloat("reactive_power"));
                                recentData.setElectricalPower(rs.getFloat("electrical_power"));
                                recentData.setPowerFactor(rs.getFloat("power_factor"));
                            }
                            reponse = gsonReponse.toJson(recentData);
                        }

but it doesn't work either, cuz my server answer only it receives a message, and I send a message only when I click on a butonn on my app. So what I'm looking for is a way to send a message to my server every five seconds without making my app crash.

  • your post miss crash stacktrace – Marcin Orlowski Apr 24 '23 at 09:41
  • You need to create a new thread for that task, if you do Thread.sleep(5000) in the main thread, you will get an "Application is not responding" error. I suggest you look into Executors and/or coroutines to execute tasks in the background. – m0skit0 Apr 24 '23 at 09:42
  • Does this answer your question? [How to run a method every X seconds](https://stackoverflow.com/questions/11434056/how-to-run-a-method-every-x-seconds) – m0skit0 Apr 24 '23 at 09:43
  • @m0skit0 Doesn't that depend upon the platform/framework? I'm guessing you may be talking about something like Android; a GUI such as Swing might instead show a beachball/hourglass during the wait; a plain UI-less application or web app might simply wait with no problem. – gidds Apr 24 '23 at 09:46
  • Thank you for all your answers, and sorry if I wasted your time, but I don't need help anymore. I remembered I could use a TimerTask on the server side aroud 5-10 minutes after I asked the question, and it runs without any problems. – Oscar Pill Apr 26 '23 at 12:43

0 Answers0