How to use “poor man's cron” with PHP?

340
November 26, 2016, at 10:46 AM

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 1

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

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.

Rent Charter Buses Company
READ ALSO
Scaffolding code of wordpress plugin

Scaffolding code of wordpress plugin

I have been given a project in which I have do the following task:

395
How to display result of PHP render in HTML ID

How to display result of PHP render in HTML ID

this is my first question hereAfter digging internet for an answer I cannot find any idea about how to deal with my issue

782
PHP soap request with certifcate

PHP soap request with certifcate

I've been trying to implement a soap request with a pem certificate and i'm just getting out of ideasI know my code should be all wrong but i have no idea what the right direction is

430
Google Firebase notifications working on console but not on API

Google Firebase notifications working on console but not on API

The notification work just fine when sent from the firebase console, but don't work when sent from the APIEven when the result displays a success: {"multicast_id":5946406103096345260,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1480093752122166%13791f60f9fd7ecd"}]}

362