Development

How to run a PHP script every 10 seconds

Whilst using cron to call PHP scripts allows for intervals as low as 1 minute sometimes you may need a lower rate, here is how to call a PHP file every 10 seconds.

Using Jquery and ajax allows for calling an XHR request every set amount of milliseconds (setInterval). In this case, it is 10000 milliseconds for 10 seconds.

The script below stored at (run.html) when called will continuously run a get request to call.php until the page/connection is closed.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
    setInterval(function () {
        $.ajax({
            url: 'call.php',
            success: function (data) {
                console.log("Success");
            }
        });
    }, 10000);
</script>

This calls call.php every 10 seconds and will write Success in the console each time it runs.

To modify this script for some GET request parameters it looks like this:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
    setInterval(function () {
        $.ajax({
            url: 'call.php',
            data: {id: 44, key: 'XJF4YS1JF6H'},
            success: function (data) {
                console.log("Success");
            }
        });
    }, 10000);
</script>

This will call call.php?id=44&key=XJF4YS1JF6H every 10 seconds.

Of course you can change the 10-second interval to 5, 15, 30 etc just remember that it is in milliseconds.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago