Skip to main content

Run a PHP Function Every X Minutes

There are 2 ways to run a PHP function every X minutes. One is to use cron job, and the other is to use AJAX.

To use the cron job, you need to have access to the server. For most shared hosting providers, this is not possible. If you have a VPS or a dedicated server, you can set up a cron job easily.

If you don’t have access to the server, you can use AJAX to run the PHP function every X minutes.

Let’s view some examples how to execute a PHP script

Create a some_file.php and add the following codes to the file:

<?php

echo "The number is: "; echo rand(1, 2000);

?>

Cron Job

//run PHP every 5 minutes
*/5 * * * * /usr/bin/php /mydomain.com/some_file.php

//run PHP every 10 minutes */10 * * * * /usr/bin/php /mydomain.com/some_file.php

AJAX

<html>
<head>
<script>
function someFunction() {
  var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.querySelectorAll(".result")[0].innerText = this.responseText;
      }
    };
    xmlhttp.open("GET", "some_file.php", true);
    xmlhttp.send();
}
setInterval("someFunction", 10000);
</script>
</head>
<body>

<div class="result"></div>

</body> </html>

By continuing to use the site, you agree to the use of cookies.