Make the code continue to work after closing the page

I have a While loop (function) that runs for several minutes, sometimes it can take up to 10 minutes, and sometimes 30 minutes.

I do not want the user to wait for the web page window to open for 30 minutes, I want the user to close the window and continue its cycle.

I want the user to open a web page by clicking on a button to launch this function, and then close the page and let the function work on its own.

Is there any chance this is possible?

+4
source share
6 answers

If the script timeout parameter ( max_execution_time in php.ini ) is not a problem for you, you can use ignore_user_abort(true) .

But usually the best solution for such tasks is to appear in the background. The Gearman extension may be of interest to you or to different versions of exec .

+2
source

You can check fastcgi_finish_request() . This allows your script to continue to work, but to "hang" a connection to the browser. Of course, it should be used carefully, otherwise you may encounter many processes running on a half-background.

Of course, this is only available with php-fpm. Otherwise, you'll be looking for things like gearman , basically any task scheduler.

+3
source

User actions do not stop the script or the like.

the script will continue until it completes or reaches a timeout (on most servers it will be 15 or 30 seconds), so if you have your own server or private, without a timeout, your script will run for 30 minutes with a user not influencing him.

What you should worry about - not letting the script run again if the user refreshes the page or visits again over a period of time.

0
source
 function execInBackground($cmd) { if (substr(php_uname(), 0, 7) == "Windows"){ pclose(popen("start /B ". $cmd, "r")); } else { exec($cmd . " > /dev/null &"); } } 

Or db + cron solution.

0
source

I have done this in the past.

 class Task { function add($command) function execute(); } class TaskManager { function run(){ $task->execute(); } } 

Tasks are added to the queue (DB, flatfile, cut out of stone, as you wish) as a script command or shell. Then the TaskManager starts as a service (some good comments at http://php.net/manual/en/function.pcntl-fork.php ) and continues to take the first element from the queue and execute it.

This way you can serve long-running tasks in the background, and you don't have many rogue processes.

0
source

I think you need to rethink why you have been taking such long processes in the interface for so long. Why not put the work queue in place and let the background daemons or maintenance process go as fast as they can.

What happens now if many people have open processes and php cannot create new threads?

What happens when errors occur or during reprocessing?

0
source

All Articles