PHP-script refresh it self and restart execution-time

只谈情不闲聊 提交于 2020-06-29 03:33:07

问题


I have an array with about 500+ elements. These elements will be checked in a function and then I will have to grab data from an API for each element (every element is one query), that does not allow me that much requests in a short time. I will have, to run a delayed loop, that will very likely exceed 30 secs.

What I want is, that my PHP-script should do a certain amount of checks/requests and remove from the "todo"-list and then self refresh and continue the jobafter ~2 sec.

A cronjob will start this php-script.

How can I manage PHP to restart a script after "work is done" or after some kind of "failure" occurs? It depends on this thing, on how I store the data from the "todo-list"-array into either a file, or a $_SESSION. Don't want to store this into a DB.

How can I solve this without the need to setup something on the server, or outside of the script itself?


回答1:


PHP life cycle is a request based, i.e. it can't be refreshed by itself.

You can either use:

  1. The cronjob to do some work on the background
  2. The Javascript on timer to launch a new request from the browser to the web server, which will execute the PHP API and return the new result. For example:
<script>
function onTimerRefreshFromApi() {
    var request = new XMLHttpRequest();
    request.open('GET', '/api/url', true);

    request.onload = function () {
        if (this.status >= 200 && this.status < 400) {
            // On Success replace html
            element.innerHTML = this.response;
        } else {
            // We reached our target server, but it returned an error
        }
    };

    request.onerror = function () {
        // There was a connection error of some sort
    };

    request.send();
}

setInterval(onTimerRefreshFromApi, 1000);
</script>
  1. Use Ajax on timer in similar way as 2).
  2. Use headers to instruct the browser to do refresh as described: Refresh a page using PHP


来源:https://stackoverflow.com/questions/62280895/php-script-refresh-it-self-and-restart-execution-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!