PHP循环批处理

PHP Batch Processing For Loop

我有一个可以向其发送 GET 请求的端点,它 returns 根据限制和偏移量得到不同的结果。

https://example-foo-bar.com?l=100&o=0 // returns the first 100 items.

我想创建一个 for 循环(或者我假设的嵌套 for 循环)returns 一次 100 个项目,每次将结果添加到一个数组,直到响应结束。我有发送 curl 请求和存储结果的代码,只是在批处理部分苦苦挣扎。

类似于:

https://example-foo-bar.com?l=100&o=0

https://example-foo-bar.com?l=100&o=99

https://example-foo-bar.com?l=100&o=199

https://example-foo-bar.com?l=100&o=218 // end of response ?

我也知道总共有多少个结果,存储为$count;


我最终得到了这样的结果,但感觉这不是最佳做法:

function testLoop(){

  $limit = 100;

  $count = getCount();

  $j = ceil($count/$limit);

  for ($i = 0; $i < $j; $i++){
    $offset = $i*100;
    echo 'https://example-foo-bar?l='.$limit.'&o='.$offset.'';
  }
 }

 testLoop();

我不确定我是否理解正确。但是你在找这样的东西吗?

$offset = 0;
$limit = 100;
$run = true;
$result_array = array();
while($run) {      
  $result_array = array_merge($result_array, json_decode(file_get_contents("https://example-foo-bar.com?l=".$limit."&o=".$offset),true));
  $offset = $offset + $limit;
  if($offset == {somenumber}) {
    $run = false;
  }
}

然后使用 cron 作业调用 php 文件

  1. 创建table'schedule'并存储数据id、link_name、偏移量和状态列
  2. 将cron设置为每10分钟执行一次并首先获取状态=0的条目(一个)
  3. 将参数传递给 testLoop($limit) 以调用函数。可能整个link of only offset =0, offset =99, offset =199 这样
  4. 完成更新 status=1 后 table。
  5. 10 分钟后 cron 调用步骤 1。

将 Cron 用于此类批处理的最佳方式,您还可以使用 php-resque