How to make a schedule counting from time to time?

1

Well, I'd like to know how to create a simple scheduling, example I put a script to run every 5 minutes, for the logic it runs the first time and wait another 5 minutes to run again jumping 5 min I tried to do but did not very sure. Any help is welcome

if(time() - $row['time'] == $row['tempo'] + $row['agenda'] && $row['agenda'] >= 30){

        if($row['tempo'] <= $row['tempo'] + $row['agenda']){
            mysql_query("UPDATE 'agendamento' SET 'tempo' = tempo+".$row['agenda'].", 'tempo_anterior' = tempo_anterior+".$row['agenda']." WHERE 'id' =".$row['id'].";"); //ADICIONA + SEGUNDOS NO BANCO DE DADOS
        }

}else if($row['tempo'] > $row['agenda'] && $row['agenda'] >= 30){

    // EXECUTA MINHA FUNÇÃO SE CONTAR NO TEMPO CERTO

}
    
asked by anonymous 18.11.2017 / 05:31

1 answer

2

You have two possibilities using linux CRON or you can create a script that runs indefinitely.

Run script forever

To run the script indefinitely just do

set_time_limit(0);
while (true) {
    // código a ser executado de tempo em tempo
    if ( $quit === true ) {
        break;
    }
    sleep(300);
}

Note that I put a stop condition, making it possible to stop execution.

This is the worst way to do it for many reasons. PHP is not meant to run endlessly, as memory usage can increase dramatically as the runtime increases. Another disadvantage is the maintenance, because the script can stop and you do not know. Use this method only in the latter case.

Schedule using linux CRON

The most recommended way is to use CRON or the Windows Task Scheduler.

This is the most used way, because the script runs from time to time and even if an error occurs, the script will run again at the scheduled time.

To add your task and schedule the execution, go to the server terminal and type:

sudo crontab -e

It will open a text file where you can place the scheduled tasks following some patterns. In your case, the line to be added would look like this:

*/5 * * * * php ~/caminho/para/o/script.php

If you want a specific URL to be called, you will have to use the wget command in the task, thus:

*/5 * * * * wget -O - http://www.exemplo.com.br/script.php > /caminho/do/arquivo/para/armazenar/a/saida.txt

To learn more about CRON, read this question:

Configure Cronjob to run every 5 minutes when it is between 5 to 20 hours

If you want to better control your task scheduling, I wrote a response explaining how to create a tool by PHP to manage the runs.

link

    
18.11.2017 / 06:05