遵循此链接的好建议: How to keep checking for a file until it exists, then provide a link to it
如果永远不会创建文件,循环将永远不会结束。 在一个完美的系统中,它不应该发生,但是如果它确实如何退出该循环呢?
我有一个类似的案例:
/* More codes above */
// writing on the file
$csvfile = $foldername.$date.$version.".csv";
$csv = fopen( $csvfile, 'w+' );
foreach ($_POST['lists'] as $pref) {
fputcsv($csv, $pref, ";");
}
// close and wait IO creation
fclose($csv);
sleep(1);
// Running the Java
$exec = shell_exec("/usr/bin/java -jar $app $csvfile");
sleep(3);
$xmlfile = preg_replace('/\\.[^.\\s]{3,4}$/', '.xml', $csvfile);
if (file_exists("$csvfile") && (file_exists("$xmlfile"))){
header("Location:index.php?msg");
exit;
}
else if (!file_exists("$csvfile")){
header("Location:index.php?msgf=".basename($csvfile)." creation failed!");
exit;
}
else if (!file_exists("$xmlfile")){
header("Location:index.php?msgf=".basename($xmlfile)." creation failed!");
exit;
}
//exit;
} // Just the end
?>
(是的,错误的想法是在网址中传递变量..我已经覆盖了这些内容)
我使用sleep(N);
,因为我知道java创建文件的时间很短,对于php上的csv也是如此。
如何改进对文件的检查,在报告状态之前等待必要的时间OK或者如果没有创建文件则不正常?
答案 0 :(得分:1)
阅读完评论后,我认为"最好的循环"获得更好的答案并不是一个好问题。
当脚本需要文件时,链接脚本只是提供了一个很好的方法。该脚本将等待文件创建或永久(但创建者确保创建文件)。
更好的是,你可以给出一个特定的时间来确保文件是否存在。
如果在$objectA
之后java脚本没有创建文件(我认为这几乎是不可能的,但只是一个想法),你可以使用上面的代码:
shell_exec
上面的脚本将一直等到文件被创建或者直到达到特定的循环次数(调用循环比微秒更好,因为我不能确保每个循环都在一个循环中执行微秒)。如果您需要更多时间,可以更改周期数。