In php how to execute certain function after past X days of last execution

1

I'm developing changes and routines in a web application created in PHP and CakePHP, in case one of the routines would be a Component run every 15 days, to update an .html file As in PHP, do I check if X has been past days of the last execution of a given routine?

I thought of the following algorithm, but it is the 'smart' way to do the verification, how to code the algorithm?

1- Take the recorded milliseconds into a text file. 2- get the current milliseconds. 3- If you have nothing in the text file, or the current milliseconds are greater than or equal to, the milliseconds recorded in the file plus the value of X days in milliseconds. 4- record the current milliseconds in the text file.

    
asked by anonymous 01.08.2014 / 14:49

2 answers

6

A possibility would be something like having at least the location of the files and the information returned by filemtime () of each of them stored in a database.

Accessed by a given URL, you would see this information, and preferably DateTime , you would compare if 15 days passed and if so, it would execute its routine on the files.

This approach has at least three problems:

  • Requires someone to manually access this URL
  • If there are too many files, the routine will be overloaded, especially in the loop

    2.1 You could have timeout problems because of this

  • To solve the first problem and suddenly the other two at the same time, you would associate this with a CronJob configured to run every 15 days.

    But think to me: If a given routine should occur every 15 days, why keep a list of files, timestamps of the modification date, loops, comparisons, and so on. if you simply create a routine that affects every file every 15 days?

    Answer this question and you will find that with CronJobs you solve everything with your feet on your back. ;)

        
    01.08.2014 / 15:13
    4

    I see no problem using a common date for this calculation if you do not need this millisecond accuracy.

    My idea would be to use the DateTime class to check the difference of 15 days

    <?php
    
    // Algum metodo de alguma classe
    function getUltimaExecucao(){
    
        // Formato Y-m-d
        //$data = getLastDate();
    
        $data = '2014-06-30';
    
        return DateTime::createFromFormat('Y-m-d', $data);;
    }
    
    // Execução
    
    $dataUltimaExecucao = getUltimaExecucao();
    $dataAtual = new DateTime();
    
    $diferenca = $dataAtual->diff($dataUltimaExecucao);
    $diferencaEmDias = $diferenca->format('%a');
    
    if ($diferencaEmDias >= 15 ){
        echo "Se passaram $diferencaEmDias dias" . PHP_EOL;
    };
    
    echo "FIM";
    

    As commented on in other answers, you might want to run this function in cronjob in environment * unix, or schtasks (cmd) / New-JobTrigger (Powershell) in Windows environments.

        
    01.08.2014 / 15:21