批处理循环

Batch Processing Loop

我有一个脚本可以将 csv 解析为包含一百万行的数组。

我想用一个 cronjob 来批处理它。例如,每 100.000 行我想暂停脚本然后再次继续以防止内存泄漏等。

我现在的脚本是这样的: 这与做什么无关,但我如何在 cronjob 中分批循环遍历它?

Can i just make an cronjob what calls this script every 5 minutes and remembers where the foreach loop is paused?

$csv = file_get_contents(CSV);
$array = array_map("str_getcsv", explode("\n", $csv));

$headers = $array[0];
$number_of_records = count($array);
    for ($i = 1; $i < $number_of_records; $i++) {
      $params['body'][] = [
        'index' => [
          '_index' => INDEX,
          '_type' => TYPE,
          '_id' => $i
        ]
      ];

      // Set the right keys
      foreach ($array[$i] as $key => $value) {
        $array[$i][$headers[$key]] = $value;
        unset($array[$i][$key]);
      }

      // Loop fields
      $params['body'][] = [
        'Inrijdtijd' => $array[$i]['Inrijdtijd'],
        'Uitrijdtijd' => $array[$i]['Uitrijdtijd'],
        'Parkeerduur' => $array[$i]['Parkeerduur'],
        'Betaald' => $array[$i]['Betaald'],
        'bedrag' => $array[$i]['bedrag']
      ];

      // Every 1000 documents stop and send the bulk request
      if ($i % 100000 == 0) {
        $responses = $client->bulk($params);

        // erase the old bulk request
        $params = ['body' => []];

        // unset the bulk response when you are done to save memory
        unset($responses);
      }

      // Send the last batch if it exists
      if (!empty($params['body'])) {
        $responses = $client->bulk($params);
      }
    }

在给定的代码中,脚本总是从头开始处理,因为没有保留某种指针。

我的建议是将 CSV 文件拆分成多个部分,然后让另一个脚本逐个分析这些部分(即每 5 分钟一次)。 (然后删除文件)。

$fp = fopen(CSV, 'r');

$head   = fgets($fp);

$output = [$head];
while (!feof($fp)) {
    $output[] = fgets($fp);

    if (count($output) == 10000) {
        file_put_contents('batches/batch-' . $count . '.csv', implode("\n", $output));
        $count++;

        $output = [$head];
    }
}

if (count($output) > 1) {
    file_put_contents('batches/batch-' . $count . '.csv', implode("\n", $output));
}

现在原来的脚本每次可以处理一个文件:

$files = array_diff(scandir('batches/'), ['.', '..']);

if (count($files) > 0) {
    $file = 'batches/' . $files[0];

    // PROCESS FILE

    unlink($file);
}