In php how to run a function after past X days of last run

Asked

Viewed 1,630 times

1

I’m designing changes and routines in a web application created in PHP and Cakephp, in which case one of the routines would be a Component run every 15 days , to update a file. html As in PHP I check if it was past X days of the last execution of a certain routine?

I thought of the following algorithm, but is it the 'elegant' way of checking? , how to encode the algorithm?.

1- take the saved milliseconds in a text file. 2- take the current milliseconds. 3- if you have nothing in the text file, or the current milliseconds are greater than or equal to, the milliseconds saved in the file plus the value of X days in milliseconds. 4-save current milliseconds to text file.

2 answers

6

A possibility would be something like having at least the path 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 consult this information and preferably with Datetime, compare whether 15 days have passed and if so, perform your routine on the files.

This approach has at least three problems:

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

    2.1 You could have problems with timeout because of that

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

But think to me: If a certain routine should occur every 15 days, why keep a list of files, timestamps modification date, loops, comparisons, etc. if you simply create a routine that affects all files every 15 days resolve?

Answer that question and you will see that with Cronjobs you solve everything with your feet on your back. ;)

  • 2

    CronJobs +1

4

I see no problem using a common date for this calculation if you don’t need that millisecond precision.

My idea would be to use the class DateTime 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 in other responses, prefer to perform this function in a cronjob in the *Unix environment, or schtasks (cmd) / New-JobTrigger (Powershell) in Windows environments.

Browser other questions tagged

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