public function __construct() { $this->queue = new \SplPriorityQueue(); $this->timer = Loop\periodic(1, function () { $time = time(); while (!$this->queue->isEmpty()) { $key = $this->queue->top(); if (isset($this->expire[$key])) { if ($time <= $this->expire[$key]) { break; } unset($this->data[$key], $this->expire[$key], $this->ttl[$key]); } $this->queue->extract(); } if ($this->queue->isEmpty()) { $this->timer->stop(); } }); $this->timer->stop(); $this->timer->unreference(); }
/** * @see QueueInterface::pop() */ public function pop() { if (!$this->innerQueue->isEmpty()) { $eta = $this->innerQueue->top()->getEta(); if (!$eta || $eta->getTimestamp() <= time()) { return $this->innerQueue->extract(); } } return false; }
/** * {@inheritdoc} */ public function pop() { if (!$this->queue->isEmpty()) { $this->queue->setExtractFlags(\SplPriorityQueue::EXTR_PRIORITY); $priority = $this->queue->top(); if (time() + $priority[0] >= 0) { $this->queue->setExtractFlags(\SplPriorityQueue::EXTR_DATA); return $this->queue->extract(); } } throw new NoItemAvailableException($this); }
/** * {@inheritdoc} */ public function pop() { if ($this->queue->isEmpty()) { return; } $this->queue->setExtractFlags(\SplPriorityQueue::EXTR_PRIORITY); $priority = $this->queue->top(); if (time() + $priority[0] >= 0) { $this->queue->setExtractFlags(\SplPriorityQueue::EXTR_DATA); return $this->queue->extract(); } }
/** * @param string $event * @param array $params * @param string $context */ public function trigger($event, $params = [], $context = '') { if (empty($this->events[$event])) { return; } $queue = new \SplPriorityQueue(); foreach ($this->events[$event] as $index => $action) { $queue->insert($index, $action['prio']); } $queue->top(); while ($queue->valid()) { $index = $queue->current(); if (!empty($context)) { $contexts = explode(',', $this->events[$event][$index]['contexts']); $current_context = false; foreach ($contexts as $route) { if (fnmatch(trim($route), $context)) { $current_context = true; break; } } } else { $current_context = true; } if ($current_context && is_callable($this->events[$event][$index]['fn'])) { if (call_user_func_array($this->events[$event][$index]['fn'], $params) === false) { break; } } $queue->next(); } }
/** * 检查是否有可执行的定时任务,有的话执行 * @return void */ protected function tick() { while (!$this->_scheduler->isEmpty()) { $scheduler_data = $this->_scheduler->top(); $timer_id = $scheduler_data['data']; $next_run_time = -$scheduler_data['priority']; $time_now = microtime(true); if ($time_now >= $next_run_time) { $this->_scheduler->extract(); // 如果任务不存在,则是对应的定时器已经删除 if (!isset($this->_task[$timer_id])) { continue; } // 任务数据[func, args, flag, timer_interval] $task_data = $this->_task[$timer_id]; // 如果是持续的定时任务,再把任务加到定时队列 if ($task_data[2] === self::EV_TIMER) { $next_run_time = $time_now + $task_data[3]; $this->_scheduler->insert($timer_id, -$next_run_time); } // 尝试执行任务 try { call_user_func_array($task_data[0], $task_data[1]); } catch (\Exception $e) { echo $e; } continue; } else { // 设定超时时间 $this->_selectTimeout = ($next_run_time - $time_now) * 1000000; return; } } $this->_selectTimeout = 100000000; }
/** * Executes any pending timers. Returns the number of timers executed. * * @return int * * @internal */ public function tick() : int { $count = 0; $time = microtime(true); while (!$this->queue->isEmpty()) { list($timer, $timeout) = $this->queue->top(); if (!$this->timers->contains($timer) || $timeout !== $this->timers[$timer]) { $this->queue->extract(); // Timer was removed from queue. continue; } if ($this->timers[$timer] > $time) { // Timer at top of queue has not expired. return $count; } // Remove and execute timer. Replace timer if persistent. $this->queue->extract(); if ($timer->isPeriodic()) { $timeout = $time + $timer->getInterval(); $this->queue->insert([$timer, $timeout], -$timeout); $this->timers[$timer] = $timeout; } else { $this->timers->detach($timer); } // Execute the timer. $timer->call(); ++$count; } return $count; }
/** * Tick for timer. * @return void */ protected function tick() { while (!$this->_scheduler->isEmpty()) { $scheduler_data = $this->_scheduler->top(); $timer_id = $scheduler_data['data']; $next_run_time = -$scheduler_data['priority']; $time_now = microtime(true); if ($time_now >= $next_run_time) { $this->_scheduler->extract(); if (!isset($this->_task[$timer_id])) { continue; } // [func, args, flag, timer_interval] $task_data = $this->_task[$timer_id]; if ($task_data[2] === self::EV_TIMER) { $next_run_time = $time_now + $task_data[3]; $this->_scheduler->insert($timer_id, -$next_run_time); } call_user_func_array($task_data[0], $task_data[1]); if (isset($this->_task[$timer_id]) && $task_data[2] === self::EV_TIMER_ONCE) { $this->del($timer_id, self::EV_TIMER_ONCE); } continue; } else { $this->_selectTimeout = ($next_run_time - $time_now) * 1000000; return; } } $this->_selectTimeout = 100000000; }
/** * Get the number of microseconds until the next timer watcher is due. * * @return int or null when no timers are pending. */ protected function nextTimeout() { $time = \microtime(true); while (!$this->scheduler->isEmpty()) { list($watcher, $scheduled) = $this->scheduler->top(); if ($watcher->enabled && $watcher->scheduled === $scheduled) { return (int) \max(0, ($watcher->due - $time) * 1000000); } } }
/** * Method to instantiate the view. * * @param JModel $model The model object. * @param SplPriorityQueue $paths The paths queue. * * @since 12.1 */ public function __construct(JModel $model, SplPriorityQueue $paths = null) { parent::__construct($model); // Setup dependencies. $this->paths = isset($paths) ? $paths : $this->loadPaths(); /* T3: Add T3 html path to the priority paths of component view */ // T3 html path $component = JApplicationHelper::getComponentName(); $component = preg_replace('/[^A-Z0-9_\\.-]/i', '', $component); $t3Path = T3_PATH . '/html/' . $component . '/' . $this->getName(); // Setup the template path $this->paths->top(); $defaultPath = $this->paths->current(); $this->paths->next(); $templatePath = $this->paths->current(); // add t3 path $this->paths->insert($t3Path, 3); $this->_path['template'] = array($defaultPath, $t3Path, $templatePath); /* //T3 */ }
/** * @return int Milliseconds until next timer expires or -1 if there are no pending times. */ private function getTimeout() { while (!$this->timerQueue->isEmpty()) { list($watcher, $expiration) = $this->timerQueue->top(); $id = $watcher->id; if (!isset($this->timerExpires[$id]) || $expiration !== $this->timerExpires[$id]) { $this->timerQueue->extract(); // Timer was removed from queue. continue; } $expiration -= (int) (\microtime(true) * self::MILLISEC_PER_SEC); if ($expiration < 0) { return 0; } return $expiration; } return -1; }
/** * Get best matching locking method * * @param string $id ID to identify this lock in the system * @param int $capabilities LockingStrategyInterface::LOCK_CAPABILITY_* elements combined with bit-wise OR * @return LockingStrategyInterface Class name for a locking method * @throws LockCreateException if no locker could be created with the requested capabilities */ public function createLocker($id, $capabilities = LockingStrategyInterface::LOCK_CAPABILITY_EXCLUSIVE) { $queue = new \SplPriorityQueue(); /** @var LockingStrategyInterface $method */ foreach ($this->lockingStrategy as $method => $_) { $supportedCapabilities = $capabilities & $method::getCapabilities(); if ($supportedCapabilities === $capabilities) { $queue->insert($method, $method::getPriority()); } } if ($queue->count() > 0) { $className = $queue->top(); // We use 'new' here on purpose! // Locking might be used very early in the bootstrap process, where makeInstance() does not work return new $className($id); } throw new LockCreateException('Could not find a matching locking method with requested capabilities.', 1425990190); }
public function apply($filter, $value, $args = []) { if (!isset($this->filters[$filter])) { return $value; } if (!count($this->filters[$filter])) { return $this; } $queue = new \SplPriorityQueue(); foreach ($this->filters[$filter] as $index => $action) { $queue->insert($index, $action["prio"]); } $queue->top(); while ($queue->valid()) { $index = $queue->current(); if (is_callable($this->filters[$filter][$index]["fn"])) { $value = call_user_func_array($this->filters[$filter][$index]["fn"], [$value, $args]); } $queue->next(); } return $value; }
$memory = memory_get_usage(1); $time = microtime(1); for ($i = 0; $i < 1000; $i++) { $top = $slist->first(); } printf("\ntop slist: time: %f, memory: %d KB\n", microtime(1) - $time, round((memory_get_usage(1) - $memory) / 1000, 2)); $memory = memory_get_usage(1); $time = microtime(1); for ($i = 0; $i < 1000; $i++) { $alist->asort(); $top = key($alist); } printf("\ntop alist: time: %f, memory: %d KB\n", microtime(1) - $time, round((memory_get_usage(1) - $memory) / 1000, 2)); $memory = memory_get_usage(1); $time = microtime(1); for ($i = 0; $i < 1000; $i++) { $top = $plist->top(); } printf("\ntop plist: time: %f, memory: %d KB\n", microtime(1) - $time, round((memory_get_usage(1) - $memory) / 1000, 2)); $memory = memory_get_usage(1); $time = microtime(1); for ($i = 0; $i < 1000; $i++) { $item = $slist->get($i); } printf("\nget slist: time: %f, memory: %d KB\n", microtime(1) - $time, round((memory_get_usage(1) - $memory) / 1000, 2)); $memory = memory_get_usage(1); $time = microtime(1); for ($i = 0; $i < 1000; $i++) { $item = $alist[$i]; } printf("\nget alist: time: %f, memory: %d KB\n", microtime(1) - $time, round((memory_get_usage(1) - $memory) / 1000, 2));
<?php $priorityQueue = new SplPriorityQueue(); try { $priorityQueue->top(); } catch (RuntimeException $e) { echo "Exception: " . $e->getMessage() . PHP_EOL; }
$school_same = split(";", $school); $response = json_decode(file_get_contents('http://maps.googleapis.com/maps/api/distancematrix/json?origins=' . urlencode($home) . '&destinations=' . urlencode($school_same[0]) . '&mode=driving&language=nl-BE&sensor=false')); $distance = -(int) $response->rows[0]->elements[0]->distance->text; $pq->insert($school, $distance); $pref_array2[$id][$school] = $distance; } $pref_array[$id] = $pq; } $engage_array = []; $avn_array = []; $id_enagage = []; while (count($engage_array) < count($school_array)) { foreach ($pref_array as $id => $pq) { if (!isset($id_enagage[$id]) || !$id_enagage[$id]) { if (!$pq->isEmpty()) { $top = $pq->top(); if (!isset($engage_array[$top])) { $engage_array[$top] = $id; $id_enagage[$id] = true; //echo "$top***$id<br>"; } else { $old = $engage_array[$top]; if (!isset($avnarray[$old])) { $avnarray[$old] = avn($old, $conn, $pref_array2, $id_home); //echo "###$avnarray[$old]<br>"; } if (!isset($avnarray[$id])) { $avnarray[$id] = avn($id, $conn, $pref_array2, $id_home); //echo "!!!!!$avnarray[$id]<br>"; } if ($avnarray[$old] > $avnarray[$id]) {
<?php $priorityQueue = new SplPriorityQueue(); var_dump($priorityQueue->getExtractFlags()); $priorityQueue->insert("a", 1); $priorityQueue->insert("b", 2); $priorityQueue->insert("c", 0); echo "EXTR DEFAULT", PHP_EOL; echo "value: ", $priorityQueue->top(), PHP_EOL; $priorityQueue->setExtractFlags(SplPriorityQueue::EXTR_PRIORITY); var_dump($priorityQueue->getExtractFlags() & SplPriorityQueue::EXTR_PRIORITY); echo "EXTR_PRIORITY", PHP_EOL; echo "priority: ", $priorityQueue->top(), PHP_EOL; $priorityQueue->setExtractFlags(SplPriorityQueue::EXTR_BOTH); echo "EXTR_BOTH", PHP_EOL; print_r($priorityQueue->top()); echo "EXTR_DATA", PHP_EOL; $priorityQueue->setExtractFlags(SplPriorityQueue::EXTR_DATA); echo "value: ", $priorityQueue->top(), PHP_EOL;
protected function cleanup(OutputInterface $output) { // Recursive directory iterator $dir_it = function ($dir) { return new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST); }; // Recursive directory deletion $rmdir = function ($dir) use(&$dir_it) { foreach ($dir_it($dir) as $file) { if ($file->isLink()) { unlink($file->getPathname()); } elseif ($file->isDir()) { rmdir($file->getPathname()); } else { unlink($file->getPathname()); } } rmdir($dir); }; $further_cleanup_required = FALSE; $release_folder = $this->getReleaseDirectory(); $distributions = array_keys($this->getConfig('distribution_info')); // First, release directory cleanup foreach (new \DirectoryIterator($release_folder) as $file) { if ($file->isDot() || !$file->isDir() || $file->isLink()) { continue; } // Remove distributions which no longer exist (have been removed from the config file). if (!in_array($file->getBasename(), $distributions)) { $rmdir($file->getPathname()); $further_cleanup_required = TRUE; } else { // Clean up timestamped release directories within each distribution. // The number to keep is specified by --dirs $directories = new \SplPriorityQueue(); foreach (new \DirectoryIterator($file->getPathname()) as $dir) { if ($dir->isDot() || !$dir->isDir() || $dir->isLink()) { continue; } // Store directories keeping the last modified at the top. $directories->insert($dir->getPathname(), $dir->getCTime()); } // No further action is required for this directory. if ($directories->count() <= $this->dirs) { continue; } $further_cleanup_required = TRUE; // Timestamped release directories we want to keep for ($i = 0; $i < $this->dirs; $i++) { $directories->extract(); } // Delete all the others $directories->top(); while ($directories->valid()) { $dir = $directories->current(); $rmdir($dir); $directories->next(); } } } // No release directories were removed so no need to do any further cleanup. // (all other assets should be in use) if (FALSE == $further_cleanup_required) { return FALSE; } // Get a list of all assets that are in use (in use counts as being linked to // from a releases directory). $find_symlinks = function ($dir) use(&$dir_it) { $active_symlinks = []; foreach ($dir_it($dir) as $file) { // Ignore latest folder symlink if ($file->getBasename() != 'latest' && $file->isLink()) { $active_symlinks[] = basename($file->getRealPath()); } } return array_unique($active_symlinks); }; // Find all assets that are in use $active_symlinks = $find_symlinks($release_folder); // Get a list of all assets that are downloaded $downloads = []; $base_download_dir = $this->getBaseDownloadDirectory(); $d_it = new \DirectoryIterator($base_download_dir); foreach ($d_it as $file) { if (!$file->isDot() && $file->isDir()) { $downloads[] = $file->getBasename(); } } // Calculate which asset folders need to be removed from the downloads directory. $to_delete = array_diff($downloads, $active_symlinks); if (!empty($to_delete)) { $assets = []; foreach ($to_delete as $dir) { $rmdir($base_download_dir . '/' . $dir); $parts = explode('-', $dir); if (count($parts) == 5) { $assets[] = $parts[1] . '-' . $parts[2] . '-' . $parts[3]; } else { $assets[] = $parts[1] . '-' . $parts[2]; } $hash = array_pop($parts); $this->removeState($parts[0], $parts[1], $hash); } $this->saveAssetsDownloadState(); $output->writeln("<comment>Removed the following assets: " . join(',', $assets) . "</comment>"); } return TRUE; }
<?php $priorityQueue = new SplPriorityQueue(); $priorityQueue->top('var');
/** * Trigger event. * @param String $event * @param Array $params * @return Boolean */ public function trigger($event, $params = []) { if (!isset($this->events[$event])) { return $this; } if (!count($this->events[$event])) { return $this; } $queue = new \SplPriorityQueue(); foreach ($this->events[$event] as $index => $action) { $queue->insert($index, $action["prio"]); } $queue->top(); while ($queue->valid()) { $index = $queue->current(); if (is_callable($this->events[$event][$index]["fn"])) { if (call_user_func_array($this->events[$event][$index]["fn"], $params) === false) { break; // stop Propagation } } $queue->next(); } return $this; }