脚本宝典收集整理的这篇文章主要介绍了php – 带偏移量的递归目录迭代器,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
$ITerator = new \RecursiveiteratorIterator(new \Recursivedirectoryiterator($path,$flags)); $startTime = microtime(true); foreach($iterator as $pathName => $file){ // file PRocessing here // after 5 seconds stop and continue in the next request $elapsedSecs = (microtime(true) - $startTime); if($elapsedSecs > 5) break; }
b)问:是否可以从某一点开始循环?如何在下一个请求中从断点恢复?
我想到了两种方法.
您可以存储最后一个处理点和迭代器,并在最后一点1继续.
您可以通过调用iterator-> next()来保存迭代的最后位置并在下一个请求中快进,直到您到达要处理的下一个项目,即$lastPosition 1.
我们必须存储迭代器和lastPosition并在下一个请求中选择它们,直到
lastPosition等于迭代器中元素的总数.
或者,您可以在第一次运行时将迭代器转换为数组:$array = iterator_to_array($iterator);然后使用reduce数组方法.
(也许其他人知道如何减少迭代器对象.)
使用这种方法,您只能存储数据,这会将请求减少到0.
$starttime = time(); $endtime = $starttime + (5 * 60); // 5sec $totalElements = count($array); for($i = 0; $i <= $totalElements; $i++) { if(time() >= $endtime) { break; } DOStuffWith($array[$i]); } echo 'Processed ' . $i . ' elements in 5 seconds'; // exit condition is "totalElements to process = 0" // greater 1 means there is more work to do if( ($totalElements - $i) >= 1) { // chop off all the processed items From the inital array // and build the array for the next processing request $reduced_array = array_slice(array,$i); // save the reduced array to cache,session,disk Store($reduced_array); } else { echo 'Done.'; } // on the next request,load the array and resume the steps above...
总而言之,这是批处理,可以通过worker / job-queue更有效地完成,例如:
> @L_360_19@(参见PHP manual有一些Gearman例子.)或
> RabbitMQ / AMPQ或
>此处列出的PHP库:https://github.com/ziadoz/awesome-php#queue.
以上是脚本宝典为你收集整理的php – 带偏移量的递归目录迭代器全部内容,希望文章能够帮你解决php – 带偏移量的递归目录迭代器所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。