在PHP中并行/多线程执行文件

Sat*_*rma 3 php cron multithreading

我有一个cron文件cron/cron1.php.我为cron运行1分钟设置了这个.

所以对于下一个过程,执行需要1分钟.

现在我想在三分钟内并行运行这个文件.该文件的执行时间超过2分钟.

我可以在这样的单个文件中并行运行此文件

file1.php

<?php
      include("cron/cron1.php"); // run seperately
      sleep(5);
      include("cron/cron1.php"); // run seperately
       sleep(5);
      include("cron/cron1.php"); // run seperately 

?>
Run Code Online (Sandbox Code Playgroud)

在上面的文件cron1.php中将执行5秒的差异,但当上面的一个完成其过程.正如我告诉你的每一个cron1.php 都需要2分多钟才能完成.所以我无法实现它.

是否有任何进程或多线程或approch,以便我可以cron1.php每5秒延迟运行一次.那么我将把它file1.php作为一个cron工作.

Joe*_*ins 10

PHP支持多线程

http://php.net/pthreads

以下是您需要的逻辑类型的多线程示例:

<?php
define("SECOND", 1000000);
define("LOG",    Mutex::create());

/*
 * Log safely to stdout
 * @param string message the format string for log
 * @param ... args       the arguments for sprintf
 * @return void
 */
function slog($message, $args = []) {
    $args = func_get_args();
    if ((count($args) > 0) &&
        ($message = array_shift($args))) {
        $time = microtime(true);
        Mutex::lock(LOG);
        echo vsprintf(  
            "{$time}: {$message}\n", $args);
        Mutex::unlock(LOG);
    }
}

class MyTask extends Thread {
    public $id;
    public $done;

    public function __construct($id) {
        $this->id = $id;
        $this->done = false;
    }

    public function run() {
        slog("%s#%d entered ...", __CLASS__, $this->id);
        /* don't use sleep in threads */
        $this->synchronized(function(){
            /* simulate some work */
            $this->wait(10 * SECOND);
        });
        slog("%s#%d leaving ...", __CLASS__, $this->id);
        $this->done = true;
    }
}

$threads = [];

function get_next_id(&$threads) {
    foreach ($threads as $id => $thread) {
        if ($thread->done) {
            return $id;
        }
    }
    return count($threads);
}

do {
    slog("Main spawning ...");
    $id = get_next_id($threads);
    $threads[$id] = new MyTask($id);
    $threads[$id]->start();
    slog("Main sleeping ...");
    usleep(5 * SECOND); 
} while (1);
?>
Run Code Online (Sandbox Code Playgroud)

这将每5秒生成一个新线程,线程需要10秒才能执行.

您应该尝试通过共享一些常见的数据集来找到提高单个任务速度的方法.


lau*_*ent 5

您可以做的是同时运行多个进程,如下所示:

exec('php cron/cron1.php > /dev/null 2>&1 &');
exec('php cron/cron1.php > /dev/null 2>&1 &');
exec('php cron/cron1.php > /dev/null 2>&1 &');
Run Code Online (Sandbox Code Playgroud)

每个exec呼叫将在后台运行,因此您可以根据需要进行呼叫。