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; } 但是如何在下一个请求中从断点恢复?
a)将时间计算拉出foreach.你有一个开始时间,你想要一个5秒的运行时间,所以你可以预先计算结束时间(startime 5s).在foreach内部,只需比较时间是否大于或等于endtime,然后中断.
b)问:是否可以从某一点开始循环?如何在下一个请求中从断点恢复? 我想到了两种方法. 您可以存储最后一个处理点和迭代器,并在最后一点1继续. 或者,您可以在第一次运行时将迭代器转换为数组:$array = iterator_to_array($iterator);然后使用reduce数组方法. 代码未经测试.这只是一个快速的草案. $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更有效地完成,例如: > Gearman(参见PHP manual有一些Gearman例子.)或 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |