Consume queue (run receivers).

@throws RuntimeException When action is not called from a console
@return void
962253
public function consumeAction()
    {
        $request = $this->getRequest();

        // Make sure that we are running in a console and the user has not tricked our
        // application into running this action from a public web server.
        if (!$request instanceof ConsoleRequest) {
            throw new RuntimeException('You can only use this action from a console');
        }

        $console = $this->getServiceLocator()->get('console');

        if (!$console instanceof Console) {
            throw new RuntimeException('Cannot obtain console adapter. Are we running in a console?');
        }

        $queueName = $request->getParam('queue');
        $isVerbose = $request->getParam('verbose', false) || $request->getParam('v', false);

        $this->log(
            sprintf('Started consuming messages in queue "%s"', $queueName),
            LogLevel::INFO
        );

        if ($isVerbose) {
            $console->writeLine(
                sprintf('Consuming messages in queue "%s"', $queueName),
                ConsoleColor::LIGHT_BLUE
            );
        }

        /** @todo Output processing of each message when verbose */

        $consumerOptions = array();
        $maxRuntime = $this->getConsumerOption(self::OPTION_MAX_RUNTIME);

        if ($maxRuntime !== null) {
            $consumerOptions['max-runtime'] = (int) $maxRuntime;
        }

        $consumer = $this->getConsumer();
        $consumer->consume($this->getQueues()->create($queueName), $consumerOptions);

        $this->log(
            sprintf('Ended consuming messages in queue "%s"', $queueName),
            LogLevel::NOTICE
        );
    }
175919
public function socketPerform()
    {
        if ($this->count() == 0) {
            throw new Exception('Cannot perform if there are no requests in queue.');
        }

        $notRunning = $this->getRequestsNotRunning();
        do {
            /**
             * Apply cURL options to new requests
             */
            foreach ($notRunning as $request) {
                $this->getDefaultOptions()->applyTo($request);
                $request->getOptions()->applyTo($request);
                curl_multi_add_handle($this->mh, $request->getHandle());
                $this->running[$request->getUID()] = $request;
            }

            $runningHandles = null;
            do {
                // http://curl.haxx.se/libcurl/c/curl_multi_perform.html
                // If an added handle fails very quickly, it may never be counted as a running_handle.
                $mrc = curl_multi_exec($this->mh, $runningHandles);
            } while ($mrc === CURLM_CALL_MULTI_PERFORM);

            if ($runningHandles < count($this->running)) {
                $this->read();
            }

            $notRunning = $this->getRequestsNotRunning();
        } while (count($notRunning) > 0);
        // Why the loop? New requests might be added at runtime on 'complete' event.
        // So we need to attach them to curl_multi handle immediately.

        return $this->count() > 0;
    }
350776
public function init()
    {
        $stream = @fopen($this->config['url'], 'a');
        if (!$stream) {
            throw new \RuntimeException(sprintf("Couldn't open resource '%s'", $this->config['url']));
        }

        $this->stream = $stream;

        if (!empty($this->config['lock']) && $this->config['lock'] === true && stream_supports_lock($this->stream)) {
            $this->useLocks = true;
        }
    }
995908
@Trivial
    private void performAction(Runnable action, boolean addToQueue) {
        ExecutorService exec = executorService.getService();

        if (exec == null) {
            // If we can't find the executor service, we have to run it in place.
            action.run();
        } else {
            // If we can find the executor service, we'll add the action to the queue.
            // If the actionFuture is null (no pending actions) and the configFuture is null (no
            // pending configuration updates), we'll submit the actionsRunner to the executor
            // service to drain the queue
            //
            // configFuture is used to avoid bouncing the endpoint multiple times because of a
            // single configuration update.
            //
            // actionFuture is only set to a non-null value by kicking off the executor service here.
            // actionsRunner syncs on actionQueue, so we can't add any new actions while we are
            // draining the queue. When the queue is empty, actionFuture is explicitly set to null.
            //
            // Long story short, it prevents us from kicking off multiple executors which could run in
            // random order.
            if (addToQueue) {
                synchronized (actionQueue) {
                    actionQueue.add(action);
                    if ((actionFuture == null) && (configFuture == null)) {
                        actionFuture = exec.submit(actionsRunner);
                    }
                }
            } else {
                // Schedule immediately
                exec.submit(action);
            }
        }
    }
718494
public function indexAction()
    {
        $request = $this->getRequest();
        $type    = $request->getParam( 'type' );

        if ( ! $request instanceof ConsoleRequest )
        {
            throw new \RuntimeException( sprintf(
                '%s can only be used from a console.',
                __METHOD__
            ) );
        }

        $phpSelf = realpath( static::PHP_SELF );

        if ( empty( $phpSelf ) || ! is_file( $phpSelf ) )
        {
            throw new \RuntimeException( sprintf(
                '%s: php not found at "%s" (in "%s").',
                __METHOD__,
                static::PHP_SELF,
                getcwd()
            ) );
        }

        $result = 'Running ' . $type . ' cron(s) ...' . PHP_EOL . PHP_EOL;

        foreach ( $this->mimicSiteInfos() as $siteInfo )
        {
            $domain  = $siteInfo->getDomain();
            $process = new Process( array(
                'command'   => 'php',
                'arguments' => array(
                    $phpSelf,
                    'cron',
                    $domain,
                    $type,
                ),
                'environmentVariables'  => array(
                    'GRIDGUYZ_HOST'     => $domain,
                    'HTTP_HOST'         => $domain,
                ),
            ) );

            $result .= 'Calling process ...' . PHP_EOL .
                       $process->getRunCommand() . PHP_EOL;

            $output = tempnam( './data/', $domain );
            $descr  = array( Process::TYPE_FILE, $output, Process::MODE_APPEND );
            file_put_contents( $output, '' );

            $process->open( array(
                Process::STREAM_STDOUT => $descr,
                Process::STREAM_STDERR => $descr,
            ) );

            $return     = $process->close();
            $messages   = rtrim( file_get_contents( $output ), PHP_EOL );
            unlink( $output );

            if ( $messages )
            {
                $result .= static::PADDING . preg_replace(
                    '/[' . PHP_EOL . ']+/',
                    '$0' . static::PADDING,
                    $messages
                ) . PHP_EOL;
            }

            $result .= sprintf(
                'Process returned with #%d: %s' . PHP_EOL . PHP_EOL,
                $return,
                $return ? 'error!' : 'success.'
            );
        }

        $result .= 'Done.' . PHP_EOL;
        return $result;
    }
713597
public function run()
    {

        // register the default autoloader
        require SERVER_AUTOLOADER;

        // register shutdown handler
        register_shutdown_function(array(&$this, "shutdown"));

        // we need to register the class loaders again
        $application = $this->application;
        $application->registerClassLoaders();

        // register the applications annotation registries
        $application->registerAnnotationRegistries();

        // add the application instance to the environment
        Environment::singleton()->setAttribute(EnvironmentKeys::APPLICATION, $application);

        // create s simulated request/session ID whereas session equals request ID
        Environment::singleton()->setAttribute(EnvironmentKeys::SESSION_ID, $sessionId = SessionUtils::generateRandomString());
        Environment::singleton()->setAttribute(EnvironmentKeys::REQUEST_ID, $sessionId);

        // load application and message instance
        $message = $this->message;

        try {
            // load class name and session ID from remote method
            $queueProxy = $message->getDestination();
            $sessionId = $message->getSessionId();

            // lookup the queue and process the message
            if ($queue = $application->search(QueueContextInterface::IDENTIFIER)->locate($queueProxy)) {
                // the queues receiver type
                $queueType = $queue->getType();

                // create an intial context instance
                $initialContext = new InitialContext();
                $initialContext->injectApplication($application);

                // lookup the bean instance
                $instance = $initialContext->lookup($queueType);

                // inject the application to the receiver and process the message
                $instance->onMessage($message, $sessionId);

                // set the new message state to processed
                $message->setState(StateProcessed::get());
            }

        } catch (\Exception $e) {
            // log the exception
            \error($e->__toString());
            // set the message state to failed
            $message->setState(StateFailed::get());
        }

        // mark the job finished
        $this->finished = true;

        // set the message back to the global context
        $this->message = $message;
    }
1083382
public function consoleAction()
	{
	    $request   = $this->getRequest();
	    $service   = $this->fetchService();
	    $operation = $this->fetchOperation();
	    $query     = $this->fetchConsoleQuery();
	    
	    if (!$request instanceof ConsoleRequest) {
	        throw new \RuntimeException('You can only use this action from a console!');
	    }
	    
	    // Check flags
	    $verbose = $request->getParam('verbose') || $request->getParam('v');
	    $silent = $request->getParam('silent') || $request->getParam('s');
	    
	    $params = Json::decode(
            $query,
            Json::TYPE_ARRAY
        );
	    
	    try {
	        $data = $this->exec($service, $operation, $params, Command::CONTEXT_CLI);
	        return $this->prepareConsoleResponse($data, null, $verbose, $silent);
	    } catch (\Exception $exception) {
	        error_log($exception->getMessage() . ' (' . $exception->getFile().':'.$exception->getLine().')');
	        
	        return $this->prepareConsoleResponse(null, $exception, $verbose, $silent);
	    }
	}
349439
public function processQueues()
    {
        // consume queues for each store with a unique set of AMQP configuration
        foreach ($this->_amqpConfigHelper->getQueueConfigurationScopes() as $store) {
	    $this->_store = $store;
            $this->_consumeStoreQueues($store);
        }
        return $this;
    }
1077205
public function loadDeps()
    {
        $callback    = [$this, 'callback'];
        $queueName   = $this->getConfig(RouterConfig::COMMON_QUEUE_NAME);
        $queueConfig = $this->getConfig(RouterConfig::COMMON_QUEUE_CONFIGURATION_ID);
        
        $this->consumer = $this->server->getConsumer($this->thread, $queueName, $queueConfig, $callback);
    }
371583
private void runQueuedActions() {
        V view = viewRef == null ? null : viewRef.get();
        if (view != null) {
            while (!viewActionQueue.isEmpty()) {
                ViewAction<V> action = viewActionQueue.poll();
                action.run(view);
            }
        }
    }
902519
public function onReady()
    {
        $this->redis = \PHPDaemon\Clients\Redis\Pool::getInstance();

        $this->redis->multi(function ($multi) {
            // "OK"
            D('start multi: ' . $multi->result);

            $multi->set('test1', 'value1', function ($redis) use ($multi) {
                // "QUEUED"
                D('in multi 1: ' . $redis->result);

                $this->redis->set('test1', 'value1-new', function ($redis) {
                    // "OK", not "QUEUED"
                    D('out multi 1: ' . $redis->result);
                });

                setTimeout(function ($timer) use ($multi) {
                    // "QUEUED"
                    $multi->set('test2', 'value2', function ($redis) use ($multi) {
                        D('in multi 2: ' . $redis->result);

                        $multi->exec(function ($redis) {
                            D('exec');
                            D($redis->result);
                        });
                    });
                    $timer->free();
                }, 2e5);
            });
        });
    }
580006
public function run()
    {
        foreach ($this->pubsub as $message) {
            $kind = $message->kind;

            if ($kind !== Consumer::MESSAGE && $kind !== Consumer::PMESSAGE) {
                if (isset($this->subscriptionCallback)) {
                    $callback = $this->subscriptionCallback;
                    call_user_func($callback, $message);
                }

                continue;
            }

            if (isset($this->callbacks[$message->channel])) {
                $callback = $this->callbacks[$message->channel];
                call_user_func($callback, $message->payload);
            } elseif (isset($this->defaultCallback)) {
                $callback = $this->defaultCallback;
                call_user_func($callback, $message);
            }
        }
    }
273099
public function execute()
    {
        $queue = $this->container->getDelayedExecutionTaskQueue();
        if($queue->length() == 0){
            return;
        }
        ignore_user_abort(true);
        $queue->execute();
    }
833115
@Override
    public void run() {
        try {
            handle();
        } catch (Exception e) {
            Throwables.throwIfUnchecked(e);
            throw new RuntimeException(e);
        }
    }
987089
private function actionQueue() {
        $this->match(Token::T_ACTION);

        $action = ltrim($this->lastToken->getText(), '@');

        $this->match(Token::T_LEFT_PARENTHESIS);
        $this->match(Token::T_ID);
        $value = $this->lastToken->getText();
        $this->match(Token::T_RIGHT_PARENTHESIS);

        $this->metadata->addMetadata($action, $value);

        if (!$this->lookahead->isAnnotation()) {
            $this->lexer->gotoNextAnnotation();
            $this->consume();
        }
    }
175087
public function queueWithMaximumRuntime()
    {
        return collect($this->measuredQueues())->sortBy(function ($queue) {
            if ($snapshots = $this->connection()->zrange('snapshot:queue:'.$queue, -1, 1)) {
                return json_decode($snapshots[0])->runtime;
            }
        })->last();
    }
1312689
@Override
    public void run() throws Exception {
        QueueContainer queueContainer = getContainer();
        if (queueContainer.hasEnoughCapacity(txSize + 1)) {
            response = queueContainer.txnOfferReserve(transactionId);
        }
    }