/** * Initialize your logic and do whatever you want external * @param ThreadCommunicator $communicator */ public function InitializeExternal(ThreadCommunicator $communicator) { //your complicated work goes here for ($i = 0; $i < 10; $i++) { echo "Doing complicated work {$i} / 10" . PHP_EOL; sleep(1); } echo "After complete the Thread is closed automatically" . PHP_EOL; } } $loop = ForkableFactory::create(); $thread = new EchoThread($loop); //Let the thread work for some seconds then kill and start again $loop->addPeriodicTimer(3, function () use($thread) { //check if thread is running if ($thread->isRunning()) { echo "Thread is Running... Kill it!" . PHP_EOL; //cancel everything the thread is doing $thread->kill(); } else { echo "Thread is not running... Start Working!" . PHP_EOL; //cancel everything the thread is doing $thread->start(); } }); //stop process after 30 seconds, otherwise it runs forever $loop->addTimer(30, function (TimerInterface $timer) use($thread) {
*/ public function InitializeExternal(ThreadCommunicator $communicator) { //your complicated work goes here for ($i = 0; $i < 10; $i++) { echo "Doing complicated work {$i} / 10" . PHP_EOL; sleep(1); } echo "After complete you can close the thread" . PHP_EOL; $this->kill(); } } //Extends the default loop from React\EventLoop $loop = ForkableFactory::create(); //This is the thread instance. You can have as many instances as you like $thread = new EchoThread($loop); //Starting the work now $thread->start(); //you can do something in parent without affecting performance $loop->addPeriodicTimer(1, function (TimerInterface $timer) use($thread) { if ($thread->isRunning()) { echo "Thread is still running" . PHP_EOL; } else { //also the thread is done //it can take some seconds for the parent to determine echo "Thread is done" . PHP_EOL; $timer->cancel(); //we end the parent here $timer->getLoop()->stop(); } });