How to run a PHP function multiple times?

2

I have this function in PHP, it runs a Python code 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 this?

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
}
    
asked by anonymous 01.11.2016 / 15:10

5 answers

7

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

I think it's best to use Ajax and popular a DIV, for example:

foo / temperatura.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 this:

<!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>
    
01.11.2016 / 16:19
3

Note: Since I did not give more details about running the function, I declined to show an example of how to repeat execution in PHP only, as if it were a script language to execute directly on the operating system (not the web). I will not answer the second case, since the @GuilhermeNascimento is complete and will answer you.

You will have to call the function multiple times, waiting a certain amount of time with each call.

For this, you can use the sleep function, it receives as a parameter the number of seconds the script will wait until it continues the implementation.

while(true){
    $valor = retornaTemperatura();
    sleep(2);
}
    
01.11.2016 / 15:21
2

You can do this:

while(true) {
    retornaTemperatura();
    sleep(2);
}
    
01.11.2016 / 15:20
1

The best way to do this is to create 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 you can follow this example .

However, if this script will run only when run (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
}
    
01.11.2016 / 17:40
-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 it will run and how long you wait.

    
01.11.2016 / 15:49