How to run a PHP function multiple times?

Asked

Viewed 3,011 times

2

I have this function in PHP, it runs a code in Python that returns the temperature coming from the Arduino.

I need it to run every 2 seconds so I can display the updated information on the browser screen.

What would be the best way to do that?

function retornaTemperatura()
{
    $comando = escapeshellcmd('temperatura.py');// Local do arquivo python
    return shell_exec($comando);// retorna o valor do py para exibir ou mandar para  um banco de dados
}
  • "Display onscreen updated information". Will you do this via command line or browser? You did not detail this in the question. They are two different paths.

  • I want to display in the browser

  • 1

    Creates a cron task every 2 seconds on the server to run your script.

  • It could do the opposite where Adian itself sends the information instead of always checking the device every second. The "wear and tear" is less. But as this is not what you asked, I will avoid answering.

5 answers

7


Web is something that will always have the complete answer, if using a sleep you will have problems, headaches, especially if you have session_start, understand that I am not saying that Sleep is bad, I am just saying that the use of the proposed way in the other answers is not ideal.

I believe the best is to use Ajax and popular a DIV, for example:

foo/temperature.php

<?php
function retornaTemperatura()
{
    // Local do arquivo python
    $comando = escapeshellcmd('temperatura.py');

    // retorna o valor do py para exibir ou mandar para  um banco de dados
    return shell_exec($comando);
}

echo retornaTemperatura();

And on your page call something like that:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

<div id="temperatura"></div>

<script type="text/javascript">
function temperatura()
{
    var el = document.getElementById("temperatura");
    var segundos = 2; //2 segundos de espera
    var oReq = new XMLHttpRequest();

    //Defina como true
    oReq.open("GET", "/foo/temperatura.php", true);

    //Função assíncrona que aguarda a resposta
    oReq.onreadystatechange = function()
    {
        if (oReq.readyState == 4) {
            if (oReq.status == 200) {
                el.innerHTML = oReq.responseText;
            }

            setTimeout(temperatura, segundos * 1000);
        }
    };

    //Envia a requisição, mas a resposta fica sendo aguardada em Background
    oReq.send(null);
}
</script>
</body>
</html>
  • 1

    Thank you so much!! That’s exactly what I needed

3

You can do it like this:

while(true) {
    retornaTemperatura();
    sleep(2);
}

3

Obs.: As no further details were given about the execution of the function, I refrained to show an example of how to repeat the execution in PHP only, as if it were a scripting language to be executed directly in the operating system (and not by the web). I will not formulate an answer to the second case, because the @Guillhermenascimento is complete and will suit you.


You will have to call the function several times, waiting a certain time interval each call.

For this, it is possible to use the function sleep, it takes as parameter the amount of seconds the script will wait to continue execution.

while(true){
    $valor = retornaTemperatura();
    sleep(2);
}

1

The best way to do this is by creating a task scheduler to run your script every 2 seconds. To do this, it will depend on which server is windows or linux, and a certain configuration in apache.

For Linux server:

crontab -e
2/* * * * * /usr/local/bin/php /usr/var/www/seu_script.php 

For windows can follow this example.

However, if this script will only run when executed (once), you can do something like this:

function retornaTemperatura()
{
   $comando = escapeshellcmd('temperatura.py');// Local do arquivo python
   echo shell_exec($comando);
}
while (true) {
    try {
        retornaTemperatura();
    } catch (Exception $e) {
      echo "<meta http-equiv='refresh'" .
           "content='2;url=" . $_SERVER['SCRIPT_NAME'] . "'>";
    }
    sleep(2); // aguarda 2 segundos
}
  • 1

    Sorry, the examples are good, but CRONTAB is something that has nothing to do with web page, it runs as CLI, will never reach such result for the user, and the second example has no need of Sleep when excetpion occurs, since the goal has 2s, it would be better to move it into the try, are only tips. Please understand as a constructive criticism ;)

-1

or if you want to limit the number of executions you can do so

$num_max=10;
$delay=1; // 1 segundo de pausa entre cada execução
for($i=1;$i<=$num_max;$i++){
    retornaTemperatura();
    sleep($delay);
}

so you control how many times you will run and what waiting time you have.

Browser other questions tagged

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