user1589375 user1589375 - 12 days ago 5
PHP Question

How to use "poor man's cron" with PHP?

I'm trying to implement a "poor man's cron" to run my PHP script only every 10 minutes (if no one visits the page it doesn't run until someone does)

Here is what I have:

$current_time = time();

if($current_time >= $last_run + (60 * 10)) {
echo 'foo';
$last_run = time();
} else {
echo 'bar';
}


What I'm expecting to get is "foo" on the screen once and when I refresh the page I want to see "bar". If I refresh the page after 10 minutes it should be "foo" again for once and then "bar" until another 10 minutes has passed.

Currently it prints out "foo" all the time.

Answer

Variables don't hold their value after execution finishes. All memory is cleared when the PHP script finishes, meaning the next time the script is run, PHP will not know what $last_run was. You need to store $last_run somehow, possibly using the filesystem or database.

Using the filesystem, you could do:

$last_run = file_get_contents('lastrun.txt');
if (!$last_run || $current_time >= $last_run + (60 * 10)) {
   echo 'foo';
   file_put_contents('lastrun.txt', time());
} else {
    echo 'bar';
}