Run actions for the core of the application itself.

@param string|array $tasks

@return string
547655
public function runForApplication($tasks)
    {
        $folder = $this->config->getContextually('remote.directories.subdirectory');
        $folder = $this->releasesManager->getCurrentReleasePath($folder);

        return $this->modulable->runInFolder($folder, $tasks);
    }
564319
public function start($args = array())
    {
        $arg = $this->formatArgs($args);

        /**
         * Arguments and Options
         *
         */
        if (!empty($arg)) {
            $this->prepper
                 ->load($arg['task'])
                 ->loadParams($arg['params'])
                 ->prep($arg['action']);

            $this->dispatcher->setTaskName($arg['task']);
            $this->dispatcher->setActionName($arg['action']);
            $this->dispatcher->setParams($arg['params']);
        }

        $this->di->setShared('library', $this->library);
        $this->dispatcher->setDI($this->di);

        return $this->dispatcher->dispatch();
    }
469666
public function start(array $tasks)
    {
        foreach ($tasks as $task) {
            if (!isset($this->tasks[$task])) {
                throw new \RuntimeException('The task "' . $task . '" does not exists.');
            }

            Output::out(sprintf(
                '[%s] Starting task "%s"',
                Output::colorize((new \DateTime())->format('H:i:s'), 'light_gray'),
                Output::colorize($task, 'light_cyan')
            ));

            $start = microtime(true);
            $callback = $this->tasks[$task];
            $callback($this);

            Output::out(sprintf(
                '[%s] Task "%s" has finished in %s',
                Output::colorize((new \DateTime())->format('H:i:s'), 'light_gray'),
                Output::colorize($task, 'light_cyan'),
                Output::colorize(
                    sprintf(
                        '%s seconds',
                        round(microtime(true) - $start, 4)
                    ),
                    'magenta'
                )
            ));
        }
    }
1287345
public function execute(array $jobs)
    {
        $report = new CronReport();

        $this->prepareSets($jobs);
        $this->startProcesses($report);

        return $report;
    }
1057843
public function setActions($actions)
    {
        if ($this->getState() != self::INIT) {
            throw new \RuntimeException('Invalid state.');
        }

        if (count($actions) == 0) {
            $this->setState(self::INVALID);
            throw new \RuntimeException('No actions given.');
        }

        $this->actions = array_combine($actions, $actions);
        $this->setState(self::REGISTER);

        return $this;
    }
509673
public function dispatch(\Closure $task, $middlewares = null)
    {
        is_array($middlewares) || $middlewares = $this->getMiddlewares();

        $beforeReturnValue = $this->before($middlewares);

        if ($beforeReturnValue === false || $beforeReturnValue !== true) {
            return $beforeReturnValue;
        }

        $this->setPayload($task());

        $afterReturnValue = $this->after(array_reverse($middlewares));

        if ($afterReturnValue === false || $afterReturnValue !== true) {
            return $afterReturnValue;
        }

        return $this->getPayload();
    }
796904
protected function _run(array $task) {
		$this->ProcessManager->fork(function () use ($task) {
			$this->_makeRunner($task)->start();
		});
	}
559329
public function define($task, $commands)
    {
        foreach ($this->connections as $connection) {
            $connection->define($task, $commands);
        }
    }
1045138
public static function checkAndRunTasks($tasks)
    {
        $date = date('Y-m-d H:i:s');
        foreach ($tasks as $t) {
            /**
             * @var TaskInterface $t
             */
            if (TaskInterface::TASK_STATUS_ACTIVE != $t->getStatus()) {
                continue;
            }

            try {
                $cron = CronExpression::factory($t->getTime());

                if ($cron->isDue($date)) {
                    self::runTask($t);
                }
            } catch (\Exception $e) {
                echo 'Caught an exception: ' . get_class($e) . ': ' . PHP_EOL . $e->getMessage() . PHP_EOL;
            }
        }
    }
454039
public function executeTask($tasks)
    {
        return $this->explainer->displayBelow(function () use ($tasks) {
            return $this->builder->buildTask($tasks)->fire();
        });
    }
706270
public function runTask($task, WorkflowProgress $wp)
    {
        $wpr = parent::runTask($task, $wp);
        if (!is_object($wpr) && method_exists($this, $task)) {
            if ($task == 'cancel') {
                // we check to see if any other outstanding workflowprogress requests have this id
                // if they don't we proceed
                $db = Loader::db();
                $num = $db->GetOne('select count(wpID) as total from WorkflowProgress where wpID <> ? and wrID = ? and wpIsCompleted = 0',
                    array(
                        $wp->getWorkflowProgressID(),
                        $this->getWorkflowRequestID()
                    ));
                if ($num == 0) {
                    $wpr = call_user_func_array(array($this, $task), array($wp));

                    return $wpr;
                }
            }
        }

        return $wpr;
    }
698886
protected function runTasks(OutputInterface $output, $tasks)
    {
        if (count($tasks) == 0) {
            $output->writeln(sprintf('    No tasks defined for <fg=black;options=bold>%s</> stage', $this->getStageName()));
            $output->writeln('');
            return true;
        }

        if ($this->runtime->getHostName() !== null) {
            $output->writeln(sprintf('    Starting <fg=black;options=bold>%s</> tasks on host <fg=black;options=bold>%s</>:', $this->getStageName(), $this->runtime->getHostName()));
        } else {
            $output->writeln(sprintf('    Starting <fg=black;options=bold>%s</> tasks:', $this->getStageName()));
        }

        $totalTasks = count($tasks);
        $succeededTasks = 0;

        foreach ($tasks as $taskName) {
            /** @var AbstractTask $task */
            $task = $this->taskFactory->get($taskName);
            $output->write(sprintf('        Running <fg=magenta>%s</> ... ', $task->getDescription()));
            $this->log(sprintf('Running task %s (%s)', $task->getDescription(), $task->getName()));

            if ($this->runtime->inRollback() && !$task instanceof ExecuteOnRollbackInterface) {
                $succeededTasks++;
                $output->writeln('<fg=yellow>SKIPPED</>');
                $this->log(sprintf('Task %s (%s) finished with SKIPPED, it was in a Rollback', $task->getDescription(), $task->getName()));
            } else {
                try {
                    if ($task->execute()) {
                        $succeededTasks++;
                        $output->writeln('<fg=green>OK</>');
                        $this->log(sprintf('Task %s (%s) finished with OK', $task->getDescription(), $task->getName()));
                    } else {
                        $output->writeln('<fg=red>FAIL</>');
                        $this->statusCode = 180;
                        $this->log(sprintf('Task %s (%s) finished with FAIL', $task->getDescription(), $task->getName()));
                    }
                } catch (SkipException $exception) {
                    $succeededTasks++;
                    $output->writeln('<fg=yellow>SKIPPED</>');
                    $this->log(sprintf('Task %s (%s) finished with SKIPPED, thrown SkipException', $task->getDescription(), $task->getName()));
                } catch (ErrorException $exception) {
                    $output->writeln(sprintf('<fg=red>ERROR</> [%s]', $exception->getTrimmedMessage()));
                    $this->log(sprintf('Task %s (%s) finished with FAIL, with Error "%s"', $task->getDescription(), $task->getName(), $exception->getMessage()));
                    $this->statusCode = 190;
                }
            }

            if ($this->statusCode !== 0) {
                break;
            }
        }

        $alertColor = 'red';
        if ($succeededTasks == $totalTasks) {
            $alertColor = 'green';
        }

        $output->writeln(sprintf('    Finished <fg=%s>%d/%d</> tasks for <fg=black;options=bold>%s</>.', $alertColor, $succeededTasks, $totalTasks, $this->getStageName()));
        $output->writeln('');

        return ($succeededTasks == $totalTasks);
    }
1057266
protected function renderProgressBar(array $task): void
    {
        // Use a progress bar to indicate how far a long the re-indexing has come
        $progressBar = null;

        do {
            $response = ['completed' => false];

            // Ignore ServerErrorResponseException, re-indexing can make these requests time out
            try {
                $response = $this->elasticsearchService->tasks()->get([
                    'task_id' => $task['task'],
                ]);

                $total = $response['task']['status']['total'];

                // Initialize the progress bar once Elasticsearch knows the total amount of items
                if ($progressBar === null && $total > 0) {
                    $progressBar = new ProgressBar(new ConsoleOutput(), $total);
                } elseif ($progressBar !== null) {
                    $progressBar->setProgress($response['task']['status']['created']);
                }
            } catch (ServerErrorResponseException $e) {
            }

            sleep(1);
        } while ((bool)$response['completed'] === false);

        // For very short migrations we may never get a progress bar, because the task finishes too quickly
        if ($progressBar !== null) {
            $progressBar->finish();
        }

        echo PHP_EOL;
    }
783228
public function runTask($taskId, $context = array())
    {
        $param =  array(
            'actionName' => 'runTask',
            'authPass'   => $this->getConfig('password'),
            'authUser'   => $this->getConfig('login'),
            'taskId'     => $taskId,
            'mode'       => 'synchronous'
        );

        if ($this->getConfig('context') != '' && is_array($this->getConfig('context'))) {
            $context = array_merge($this->getConfig('context'), $context);
        }

        if (!empty($context) && is_array($context)) {
            $param['context'] = $context;
        }

        return $this->getContent($this->doRequest($this->get('?'. $this->getJsonEncoded($param))));
    }
472484
public function addMultiple(array $tasks): \BearFramework\Tasks
    {
        $taskLists = [];
        foreach ($tasks as $index => $task) {
            if (!isset($task['definitionID'])) {
                throw new \Exception('The definitionID key is missing for task with index ' . $index);
            }
            if (!is_string($task['definitionID'])) {
                throw new \Exception('The definitionID key must be of type string for index ' . $index);
            }
            $listID = '';
            $startTime = null;
            if (isset($task['options'])) {
                if (is_array($task['options'])) {
                    if (isset($task['options']['listID'])) {
                        $listID = (string) $task['options']['listID'];
                    }
                    if (isset($task['options']['startTime'])) {
                        $startTime = (int) $task['options']['startTime'];
                    }
                } else {
                    throw new \Exception('The \'options\' key must be of type array for index ' . $index);
                }
            }
            if (!isset($taskLists[$listID])) {
                $taskLists[$listID] = [
                    'minStartTime' => null,
                    'data' => []
                ];
            }
            if ($startTime !== null && ($taskLists[$listID]['minStartTime'] === null || $startTime < $taskLists[$listID]['minStartTime'])) {
                $taskLists[$listID]['minStartTime'] = $startTime;
            }
            $taskLists[$listID]['data'][] = $task;
        }
        foreach ($taskLists as $listID => $taskListData) {
            $options = [];
            $options['listID'] = $listID;
            if ($taskListData['minStartTime'] !== null) {
                $options['startTime'] = $taskListData['minStartTime'];
            }
            $this->add('--internal-add-multiple-task-definition', $taskListData['data'], $options);
        }
        return $this;
    }
460317
public function runTaskNow($taskName)
    {
        $tasks = $this->loader->loadTasks();

        foreach ($tasks as $task) {
            if ($task->getName() === $taskName) {
                return $this->executeTask($task);
            }
        }

        throw new \InvalidArgumentException('Task ' . $taskName . ' not found');
    }
1154670
public static function execute(\core\task\task_base $task):bool {
        global $CFG;

        if (!self::is_runnable()) {
            $redirecturl = new \moodle_url('/admin/settings.php', ['section' => 'systempaths']);
            throw new \moodle_exception('cannotfindthepathtothecli', 'tool_task', $redirecturl->out());
        } else {
            // Shell-escaped path to the PHP binary.
            $phpbinary = escapeshellarg(self::find_php_cli_path());

            // Shell-escaped path CLI script.
            $pathcomponents = [$CFG->dirroot, $CFG->admin, 'tool', 'task', 'cli', 'schedule_task.php'];
            $scriptpath     = escapeshellarg(implode(DIRECTORY_SEPARATOR, $pathcomponents));

            // Shell-escaped task name.
            $classname = get_class($task);
            $taskarg   = escapeshellarg("--execute={$classname}");

            // Build the CLI command.
            $command = "{$phpbinary} {$scriptpath} {$taskarg}";

            // Execute it.
            passthru($command);
        }

        return true;
    }