对于While循环,脚本暂停/重新启动以在max_execution_time下运行


For While Loop Script pause/restart to run under max_execution_time

我是用手动的方式来做这件事的,但我想可能有一种更自动的方式来做到这一点。下面的脚本必须调整1000个文件夹的大小,每个文件夹中总共有超过100K个图像(而不是每个文件夹中有100K个)。我只有两分钟的max_execution_time来运行它。它可以在两分钟内完成大约10个文件夹。但是,真的,我只想在两分钟之前暂停剧本。。。然后从它停止的地方重新开始…希望能在max_execution_time重新开始。我不知道sleep()是否能做到这一点——sleep可能会计入执行时间,不确定。

手动方式是将$count变量增加10,然后将while循环中的i$也增加10。因此,它将从停止的地方开始,一次处理10个文件夹。刷新以运行它。目前我也没有cron访问权限。

这是剧本。。。

class DevTestHelper {

//This will Go through all full size images and resize images into requested folder
function resizeGalleryImages($destFolder, $width, $height, $isCrop = false) {
$count = 1000;
$source = JPATH_SITE."/images/gallery/full";
$dest = JPATH_SITE."/images/gallery/".$destFolder;
echo 'Processing Images<br>';
//Loop through all 1000 folders 0 to 999 in the /full dir
for($i=0; $i < $count;$i++) {
    $iPath = $source.'/'.$i;
    if(is_dir($iPath)) {
            $h = opendir($iPath);
            //Loop through all the files in numbered folder
            while ($entry = readdir($h)) {
         //only read files
                if ($entry != "." && $entry != ".." &&        !is_dir($entry)) {
          $img = new GImage($source.'/'.$i.'/'.$entry);
                    $tmp = $img->resize($width, $height, true, 3);
                    if($isCrop) {
                        $tmpWidth = $tmp->getWidth();
                        $tmpHeight = $tmp->getHeight();
                        $xOffset = ($tmpWidth - $width) / 2;
                        $yOffset = ($tmpHeight - $height) / 2;
                        $tmp->crop($width, $height, $xOffset, $yOffset, false, 3);
                    }
                    $destination = $dest.'/'.$i.'/'.$entry;
                    if(!$tmp->toFile($destination)) {
                        echo 'error in creating resized image at: '.$destination.'<br>';
                  }
                 //echo $entry.'<br>';
        }
            }
        echo 'Processed: '.$i.' Folder<br>';
    }
}

您有几个不同的选项:

  1. 有一个填充队列的脚本和另一个处理队列的脚本
  2. 生成多个工作脚本以并行处理
  3. 每次调整大小后,在循环中使用set_time_limit(x)延长脚本超时时间,这样只要数据处理成功,它就会继续运行