How to keep checking for a file until it exists, then provide a link to it

余生长醉 提交于 2019-12-07 04:51:34

问题


I'm calling a Java program with a PHP system call. The Java program takes a while to run but will eventually produce a PDF file with a known filename.

I need to keep checking for this file until it exists and then serve up a link to it. I assume a while loop will be involved but I don't want it to be too resource intensive. What's a good way of doing this?


回答1:


Basically you got it right

while (!file_exists($filename)) sleep(1);
print '<a href="'.$filename.'">download PDF</a>';

the sleep gives 1 second between checks so it won't stress your CPU for nothing




回答2:


this will do the work but you may specify an additional timeout.

while( !file_exists($pathToFile) )
{
    sleep(1);
}



回答3:


If you need to send it back to the browser, you should probably investigate using an AJAX call on a setInterval timer and a PHP script that checks for the files existence. You can do this in two ways:

  1. flush() html back to the browser that includes Javascipt that starts a polling process using AJAX for the browser poll-side and your PHP script with an AJAX function to process the poll.

  2. If flush() doesn't work, then you should return the HTML of your PHP script BEFORE setting off your Java process. In that code put two AJAX calls. One that starts the actual Java process and one that starts a polling service looking for the file.

Long running scripts may timeout the browser before you can get a response from your Java application, which is why you'll likely need the browser to work asynchronously from your Java process.

On the other hand, if this is a pure PHP script running or the Java process is less than a typical browser timeout, you can just use something like:

$nofileexists = true;
while($nofilexists) { // loop until your file is there
  $nofileexists = checkFileExists(); //check to see if your file is there
  sleep(5); //sleeps for X seconds, in this case 5 before running the loop again
}

You didn't mention if this would be a high traffic call (for lots of public users) or a reporting type application. If high traffic, I would recommend the AJAX route, but if low traffic, then the code above.



来源:https://stackoverflow.com/questions/5870487/how-to-keep-checking-for-a-file-until-it-exists-then-provide-a-link-to-it

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