/** * @return ForkManager */ public function create() { $event = new ForkManagerEvent(); $eventDispatcher = new EventDispatcher(); $memoryLimitManager = new MemoryLimitManager(); $taskManager = new TaskManager(); $timeLimitManager = new TimeLimitManager(); //set default values for optional properties $memoryLimitManager->setLimitInMegaBytes(128); $memoryLimitManager->setBufferInMegaBytes(8); $timeLimitManager->setLimitInHours(1); $timeLimitManager->setBufferInMinutes(4); $manager = new ForkManager(); $manager->injectEvent($event); $manager->injectEventDispatcher($eventDispatcher); $manager->injectMemoryLimitManager($memoryLimitManager); $manager->injectTimeLimitManager($timeLimitManager); $manager->injectTaskManager($taskManager); $manager->setMaximumNumberOfThreads(16); $manager->setNumberOfMicrosecondsToCheckThreadStatus(100000); //1000000 microseconds = 1 second return $manager; }
/** * @throws RuntimeException */ public function execute() { $this->assertMandatoryPropertiesAreSet(); $this->setUpSignalHandling('signalHandler'); $this->eventDispatcher->dispatch(ForkManagerEvent::STARTING_EXECUTION, $this->createNewEvent(__METHOD__)); while ($this->taskManager->areThereOpenTasksLeft() && $this->noShutdownSignalReceived) { if ($this->timeLimitManager->isLimitReached()) { $this->eventDispatcher->dispatch(ForkManagerEvent::REACHING_TIME_LIMIT, $this->createNewEvent(__METHOD__, $this)); $this->stopAllThreads(); } else { if ($this->isMaximumMemoryLimitOfWholeThreadsReached()) { $this->eventDispatcher->dispatch(ForkManagerEvent::REACHING_TIME_LIMIT, $this->createNewEvent(__METHOD__, $this)); $this->stopNewestThread(); $this->sleep(); } else { if ($this->isMaximumNumberOfThreadsReached()) { $this->updateNumberOfRunningThreads(); $this->sleep(); } else { $task = $this->taskManager->getOpenTask(); if ($task instanceof AbstractTask) { $this->startThread($task); } } } } } $this->eventDispatcher->dispatch(ForkManagerEvent::FINISHED_EXECUTION_OF_OPEN_TASK, $this->createNewEvent(__METHOD__)); $this->eventDispatcher->dispatch(ForkManagerEvent::STARTING_WAITING_FOR_RUNNING_TASKS, $this->createNewEvent(__METHOD__)); while ($this->notAllThreadsAreFinished() && $this->noShutdownSignalReceived) { if ($this->timeLimitManager->isLimitReached()) { $this->eventDispatcher->dispatch(ForkManagerEvent::REACHING_TIME_LIMIT, $this->createNewEvent(__METHOD__, $this)); $this->stopAllThreads(); } else { if ($this->isMaximumMemoryLimitOfWholeThreadsReached()) { $this->eventDispatcher->dispatch(ForkManagerEvent::REACHING_TIME_LIMIT, $this->createNewEvent(__METHOD__, $this)); $this->stopNewestThread(); $this->sleep(); } else { $this->updateNumberOfRunningThreads(); $this->sleep(); } } } $this->eventDispatcher->dispatch(ForkManagerEvent::FINISHED_WAITING_FOR_RUNNING_TASKS, $this->createNewEvent(__METHOD__)); $this->eventDispatcher->dispatch(ForkManagerEvent::FINISHED_EXECUTION, $this->createNewEvent(__METHOD__)); }