user1589375
user1589375

Reputation: 513

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.

Upvotes: 1

Views: 1231

Answers (2)

OptimusCrime
OptimusCrime

Reputation: 14863

This is unfortunately not how PHP works. PHP starts a new process when you access the web server, and dies afterwards. You would need a script that runs forever, using something like:

while (true) {
    // Check if we should do anything, or just keep spinning
}

However, PHP was not designed for these kinds of tasks, and this script will most likely die sooner or later for either max execution time, memory limits or something else.

A functional "poor mans cronjob" would instead require you to check the current timestamp and do whatever should be done since the last visit before you continue. This would "fake" the illusion of having a cron job running.

Upvotes: 2

Devon Bessemer
Devon Bessemer

Reputation: 35347

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';
}

Upvotes: 3

Related Questions