并行执行多个 php 脚本

Executing Multiple php scripts in Parallel

我必须执行 100 多个 php 并行执行的脚本,每个 php 脚本在数据库中插入新数据并更新一些以前的记录。

例如,每个脚本 url 会是这样的:

示例。com/update.php?data-from-project-1.com
example.com/update.php?data-from-project-2.com
example.com/update.php?data-from-project-2.com
那么...

更新页面的工作类似于:
Update.php

<?php
//insert some new records from project data
//update some records
?>

我正在尝试做:
Cron 作业页面:

$urls=array("data-from-project-2.com", "data-from-project-2.com",....)
for ($index = 0; $index < count($urls); $index++) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "update.php?$urls[$index]");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch); }

但我想这会按顺序执行所有页面并且也会产生超时问题。无论如何通过 cron 作业页面并行执行它们。我不需要任何输出,他们只需要更新数据库。任何帮助,将不胜感激。谢谢

我想假装这是我的回复,但 SO 的这个回答应该涵盖它。

Executing multiple PHP scripts in parallel, and being notified when finished

使用Php 线程。简单例子:

<?php

class workerThread extends Thread {
public function __construct($i){
  $this->i=$i;
}

public function run(){
  while(true){
   echo $this->i;
   sleep(1);
  }
}
}

for($i=0;$i<50;$i++){
$workers[$i]=new workerThread($i);
$workers[$i]->start();
}

?>

您可以在每个线程中编写每个更新。但我建议您为每个线程创建一些批次。因为每个线程也需要一些时间来启动。 或者每个线程可能使用全局数组变量的某些部分 "urls" (start_index, end_index)

您可以使用 PHP 的 curl_multi_init() 异步处理您的任务。

I highly recommend this tutorial