Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a second php file with a 20 second delay

I need to run a second php file in the background. The problem is that this file needs to only run 20 seconds after the current file has completed. I have used exec("php test_script.php") to run the file but I cant get it to wait. If I use sleep() if halts my current script.

To be a bit more specific. I am uploading a file to a remote server. I then need to wait approximately 20 seconds after completing the upload to check the server for a response. In the meantime I would like to carry on with the current file. The second file will do what is needed in the background. At the moment I have to wait then run the second file.

like image 332
user1097983 Avatar asked Feb 23 '23 03:02

user1097983


1 Answers

The simplest solution to this can be found here. Basically, execute your script like this:

exec('test_script.php >/tmp/output.txt &');

Notice the ampersand ('&') at the end, this will make the command run in the background! You can delay the script by 20 seconds by adding the sleep in test_script.php.

Your other options are to trigger the second script either via Javascript (AJAX) from client side; or have a process running in the background (or regularly via cron job) which is checking some kind of common data (e.g. database) for requests, and which will get active if such a request needs to be processed.

JavaScript is not an option if the script has to run, since the user could decide to navigate away from your page, or not be executing JavaScript, or be malicious and decide just not do execute that particular JavaScript.

like image 135
codeling Avatar answered Feb 24 '23 16:02

codeling