Execute php script on server every 5 minutes

10,546

Solution 1

It would not surprise me that a hosting service would protect its servers from getting overloaded with long-running scripts, and would configure a time-out after which such scripts are aborted (see PHP: Runtime Configuration Settings and max_execution_time in particular).

If you have a PC that can stay turned on, an alternative solution would be to let it send a request to the server every 5 minutes:

<?php
    // Your PHP code that has to be executed every 5 minutes comes here
?>
<script>
setTimeout(function () { window.location.reload(); }, 5*60*1000);
// just show current time stamp to see time of last refresh.
document.write(new Date());
</script>

Solution 2

There is a max_execution_time parameter which stops the script if it takes too long, 30 seconds by default, see the docs - http://php.net/manual/en/info.configuration.php#ini.max-execution-time.

You can try to do set_time_limit(0) at the beginning of your script (see http://php.net/manual/en/function.set-time-limit.php), or change the max_execution_time parameter itself.

But in general, I would not go with such solution, it is not very reliable. Better find a hosting where you can use cron or you can try to look for some external service which will ping your script every 5 minutes (probably you can use services which monitor the web application health).

Share:
10,546
Benvaulter
Author by

Benvaulter

Just a simple coder

Updated on June 04, 2022

Comments

  • Benvaulter
    Benvaulter almost 2 years

    I want to run a php script every 5 minutes that processes some simple mysql queries to identify potential errors and in case an error is recorded as a database entry the php script sends out an email.

    From my research, it seems like cron jobs (or task schedulers) usually take care of running scripts at specified times, however I cannot find this option anywhere at the hosting service I am using (who runs "Parallels Plesk Panel 11.0.9" as the management interface I can access).

    Therefore I tried the following "trick":

    <?php
    $active = $_GET["a"];
    set_time_limit(0);
    while($active == 1){
        include 'alert_exe.php';
        sleep(300); // execute script every 5 mins
    }
    ?>
    

    To active the script I enter the url (".../alert.php?a=1"). This works fine for a couple of minutes, however it seems after 2 or 3 minutes the script stops executing.

    Any idea how I can prevent the stopping of the script or alternative suggestions how to achieve the automatic execution of a script every 5minutes (without being able to access cron jobs)?

    Thanks!