Run file in parallel / multithreading in PHP

I have a cron file cron/cron1.php. I set this for cron running 1 minute.

therefore, the next process will take 1 minute.

Now I want to run this file in parallel three times a minute. This file takes a runtime of more than 2 minutes.

I can run this file in parallel in a single file like this

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 

?>

in the above file, a cron1.phpdifference of 5 seconds will be executed, but when its process will be completed over it. as I told you, each cron1.phpwill take more than 2 minutes. therefore, I could not achieve this.

is there any process or multithreading or matching so that I can run every cron1.phpevery 5 seconds of delay. then I will install file1.phpas a cron job.

+3
2

, - :

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 &');

exec , , .

+3

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);
?>

5 , 10 .

, , .

+8

All Articles