1

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.

1
  • 1
    HTTP request timeout is around 30 seconds. If you want to refresh the page periodically, do it on client side (via javascript, or <meta http-equiv="refresh" content="600"> Commented Nov 25, 2016 at 17:18

2 Answers 2

3

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';
}
Sign up to request clarification or add additional context in comments.

1 Comment

This did the trick! I must have mixed some other language there when I tried to store the value straight into the variable. Haven't used PHP in a long time. Need to wait 5 mins until I can accept this as an answer. Thank you!
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.

2 Comments

Are you sure that while(true) won't overload the server and return a 500 error code?
@AniketSahrawat You'd most likely need some sort of sleep or something in this loop. It was meant as a "this is how you would have to do it, but it won't work". Constructing a while (true) given the right php settings would work, but the script would die after a while.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.