dailyAt

@param int   $hour
@param mixed $task

@return  ScheduleEvent

@throws \ReflectionException
@throws \Windwalker\DI\Exception\DependencyResolutionException

@since  __DEPLOY_VERSION__
770834
public function dailyAt(int $hour, $task): ScheduleEvent
    {
        return $this->cron(sprintf('0 %d * * *', $hour), $task);
    }
147727
public function update(Task $task): Task
    {
        $id = $task->getId();

        $task->setId(null);

        $response = $this->client->put($this->prepareUrlForKey('update-task', ['id' => $id]), [], $task->jsonSerialize());
        $responseData = $response->getDecodedBody();

        return new Task($responseData);
    }
722922
private Task taskToBeRescheduled(Task task) {
        Task taskToBeRetried = task.copy();
        taskToBeRetried.setTaskId(IDGenerator.generate());
        taskToBeRetried.setRetriedTaskId(task.getTaskId());
        taskToBeRetried.setStatus(SCHEDULED);
        taskToBeRetried.setRetryCount(task.getRetryCount() + 1);
        taskToBeRetried.setRetried(false);
        taskToBeRetried.setPollCount(0);
        taskToBeRetried.setCallbackAfterSeconds(0);
        task.setRetried(true);
        return taskToBeRetried;
    }
1294542
public function dailyAt($time): self
    {
        $segments = \explode(':', $time);
        $firstSegment = (int) $segments[0];
        $secondSegment = \count($segments) > 1
            ? (int) $segments[1]
            : '0'
        ;

        return $this
            ->spliceIntoPosition(2, (string) $firstSegment)
            ->spliceIntoPosition(1, (string) $secondSegment)
        ;
    }
304059
private function rollback($task)
    {
        echo "Rollback task n°" . $task->getId() . "\r\n";
        $lineConfig = false;
        $timetable = false;
        foreach ($task->getAmqpAcks() as $ack) {
            if ($ack->getPayload()->generated == true) {
                $lineConfig = $this->getLineConfig($ack, $lineConfig);
                $timetable = $this->getTimetable($ack, $lineConfig, $timetable);
                $this->removeTmpMedia($timetable, $ack->getPayload()->timetableParams->externalStopPointId);
            }
        }
    }
281522
public function markAsExecuted(ScheduledTask $task, \DateTime $executionDate = null)
    {
        if (empty($executionDate)) {
            $executionDate = new \DateTime();
        }

        $task->setExecutionDate($executionDate);

        $this->om->persist($task);
        $this->om->flush();
    }
86636
public function set_task($task)
    {
        if (php_sapi_name() == 'cli') {
            $task = 'cli';
        }
        else if (!$this->user || !$this->user->ID) {
            $task = 'login';
        }
        else {
            $task = asciiwords($task, true) ?: 'mail';
        }

        $this->task      = $task;
        $this->comm_path = $this->url(array('task' => $this->task));

        if (!empty($_REQUEST['_framed'])) {
            $this->comm_path .= '&_framed=1';
        }

        if ($this->output) {
            $this->output->set_env('task', $this->task);
            $this->output->set_env('comm_path', $this->comm_path);
        }
    }
898701
private function commit($task)
    {
        $lineConfig = false;
        $timetable = false;
        foreach ($task->getAmqpAcks() as $ack) {
            try {
                if ($ack->getPayload()->generated == true) {
                    $lineConfig = $this->getLineConfig($ack, $lineConfig);
                    $timetable = $this->getTimetable($ack, $lineConfig, $timetable);
                    $stopPoint = $this->getStopPoint($ack, $timetable);
                    if (empty($stopPoint)) {
                        $stopPoint = new StopPoint();
                        $stopPoint->setTimetable($timetable);
                        $stopPoint->setExternalId($ack->getPayload()->timetableParams->externalStopPointId);
                    }
                    $stopPoint->setPdfHash($ack->getPayload()->generationResult->pdfHash);
                    $pdfGenerationDate = new \DateTime();
                    $pdfGenerationDate->setTimestamp($ack->getPayload()->generationResult->created);
                    $stopPoint->setPdfGenerationDate($pdfGenerationDate);
                    $this->om->persist($stopPoint);
                    $this->mediaManager->saveStopPointTimetable(
                        $timetable,
                        $stopPoint->getExternalId(),
                        $ack->getPayload()->generationResult->filepath
                    );
                    $this->removeTmpMedia($timetable, $stopPoint->getExternalId());
                } elseif (isset($ack->getPayload()->error)) {
                    throw new \Exception('Ack error msg: ' . $ack->getPayload()->error);
                }
            } catch (\Exception $e) {
                $task->fail();
                echo "ERROR during task Completion, task n°" . $task->getId() . "\n";
                echo $e->getMessage() . "\n";
            }
        }
        $task->complete();
    }
460008
public static String schedule(String schedulingPattern, Runnable task) {
		return scheduler.schedule(schedulingPattern, task);
	}
842439
public function stop(Task $task)
    {
        $task->setStatus(Task::STATUS_STOPPED);

        $this->om->persist($task);
        $this->om->flush();

        $this->notify(NotifierInterface::MESSAGE_UPDATE);

        return $task;
    }
487335
public function update(Task $task)
    {
        $this->om->persist($task);
        $this->om->flush();

        $this->notify(NotifierInterface::MESSAGE_UPDATE);

        return $task;
    }
352279
public function schedule(Task $task, callable $callback = null)
    {
        // 特殊场景回调，如清理资源
        if ($callback !== null) {
            $task->resetCallBack($callback);
        }

        /* @var $task Task */
        $task->run();

        try {
            do {
                // 迭代器检查
                if (!$task->getRoutine() instanceof \Generator) {
                    break;
                }

                // 协程异步IO
                if ($task->getRoutine()->valid() && ($task->getRoutine()->current() instanceof IBase)) {
                    break;
                }

                // 继续调度
                if (!$task->isFinished()) {
                    $this->schedule($task);
                    break;
                }

                // 请求调度结束（考虑是否回调）
                $task->resetRoutine();
                if (is_callable($task->getCallBack())) {
                    $func = $task->getCallBack();
                    $task->resetCallBack();
                    $func();
                    break;
                }
            } while (0);
        } catch (\Throwable $e) {
            $task->handleTaskException($e, null);
            $this->schedule($task);
        }

        return $this;
    }
1166101
public function dispatch(TaskContract $task, array $params = [], bool $async = true, float $timeout = 1)
    {
        $data = ['object' => $task, 'params' => $params];

        return $async ? $this->server->task($data, -1, function (Server $server, int $taskId, $data) use ($task) {
            $task->finish($data);
        }) : $this->server->taskwait($data, $timeout);
    }
762271
public function task($task, Child $parent = null)
    {
        if (empty($task)) {
            return null;
        }
        if (class_exists($task)) {
            $task_class = $task;
        } else {
            $task = str_replace('/', '\\', $task);
            $task_class = "app\\Tasks\\" . $task;
            if (!class_exists($task_class)) {
                $task_class = "Server\\Tasks\\" . $task;
                if (!class_exists($task_class)) {
                    throw new SwooleException("class task_class not exists");
                }
            }
        }
        if (!get_instance()->server->taskworker) {//工作进程返回taskproxy
            $this->_task_proxy->core_name = $task_class;
            if ($parent != null) {
                $this->_task_proxy->setContext($parent->getContext());
            }
            return AOP::getAOP($this->_task_proxy);
        }
        $task_instance = Pool::getInstance()->get($task_class);
        $task_instance->reUse();
        return $task_instance;
    }
119268
public static function action($task)
    {
        //====================================================================//
        // Stack Trace
        Splash::log()->trace();
        Splash::log()->deb("Admin => ".$task->name." (".$task->desc.")");

        //====================================================================//
        // Initial Response
        $response = self::getEmptyResponse($task);

        switch ($task->name) {
            //====================================================================//
            //  READING OF SERVER OBJECT LIST
            case SPL_F_GET_OBJECTS:
                $response->data = Splash::objects();
                if (false != $response->data) {
                    $response->result = true;
                }

                break;
            //====================================================================//
            //  READING OF SERVER WIDGETS LIST
            case SPL_F_GET_WIDGETS:
                $response->data = Splash::widgets();
                if (false != $response->data) {
                    $response->result = true;
                }

                break;
            //====================================================================//
            //  READING OF SERVER SELFTEST RESULTS
            case SPL_F_GET_SELFTEST:
                $response->result = Splash::selfTest();
                $response->data = $response->result;

                break;
            //====================================================================//
            //  READING OF SERVER INFORMATIONS
            case SPL_F_GET_INFOS:
                $response->data = Splash::informations();
                if (false != $response->data) {
                    $response->result = true;
                }

                break;
            default:
                Splash::log()->err("Admin - Requested task not found => ".$task->name);

                break;
        }

        return $response;
    }
88870
public function scheduled_tasks_table($tasks) {
        global $CFG;

        $showloglink = \core\task\logmanager::has_log_report();

        $table = new html_table();
        $table->head = [
            get_string('name'),
            get_string('component', 'tool_task'),
            get_string('edit'),
            get_string('logs'),
            get_string('lastruntime', 'tool_task'),
            get_string('nextruntime', 'tool_task'),
            get_string('taskscheduleminute', 'tool_task'),
            get_string('taskschedulehour', 'tool_task'),
            get_string('taskscheduleday', 'tool_task'),
            get_string('taskscheduledayofweek', 'tool_task'),
            get_string('taskschedulemonth', 'tool_task'),
            get_string('faildelay', 'tool_task'),
            get_string('default', 'tool_task'),
        ];

        $table->attributes['class'] = 'admintable generaltable';
        $table->colclasses = [];

        if (!$showloglink) {
            // Hide the log links.
            $table->colclasses['3'] = 'hidden';
        }

        $data = array();
        $yes = get_string('yes');
        $no = get_string('no');
        $never = get_string('never');
        $asap = get_string('asap', 'tool_task');
        $disabledstr = get_string('taskdisabled', 'tool_task');
        $plugindisabledstr = get_string('plugindisabled', 'tool_task');
        $runnabletasks = tool_task\run_from_cli::is_runnable();
        foreach ($tasks as $task) {
            $customised = $task->is_customised() ? $no : $yes;
            if (empty($CFG->preventscheduledtaskchanges)) {
                $configureurl = new moodle_url('/admin/tool/task/scheduledtasks.php', array('action'=>'edit', 'task' => get_class($task)));
                $editlink = $this->action_icon($configureurl, new pix_icon('t/edit', get_string('edittaskschedule', 'tool_task', $task->get_name())));
            } else {
                $editlink = $this->render(new pix_icon('t/locked', get_string('scheduledtaskchangesdisabled', 'tool_task')));
            }

            $loglink = '';
            if ($showloglink) {
                $loglink = $this->action_icon(
                    \core\task\logmanager::get_url_for_task_class(get_class($task)),
                    new pix_icon('e/file-text', get_string('viewlogs', 'tool_task', $task->get_name())
                ));
            }

            $namecell = new html_table_cell($task->get_name() . "\n" . html_writer::tag('span', '\\'.get_class($task),
                array('class' => 'task-class text-ltr')));
            $namecell->header = true;

            $component = $task->get_component();
            $plugininfo = null;
            list($type, $plugin) = core_component::normalize_component($component);
            if ($type === 'core') {
                $componentcell = new html_table_cell(get_string('corecomponent', 'tool_task'));
            } else {
                if ($plugininfo = core_plugin_manager::instance()->get_plugin_info($component)) {
                    $plugininfo->init_display_name();
                    $componentcell = new html_table_cell($plugininfo->displayname);
                } else {
                    $componentcell = new html_table_cell($component);
                }
            }

            $lastrun = $task->get_last_run_time() ? userdate($task->get_last_run_time()) : $never;
            $nextrun = $task->get_next_run_time();
            $disabled = false;
            if ($plugininfo && $plugininfo->is_enabled() === false && !$task->get_run_if_component_disabled()) {
                $disabled = true;
                $nextrun = $plugindisabledstr;
            } else if ($task->get_disabled()) {
                $disabled = true;
                $nextrun = $disabledstr;
            } else if ($nextrun > time()) {
                $nextrun = userdate($nextrun);
            } else {
                $nextrun = $asap;
            }

            $runnow = '';
            if ( ! $disabled && get_config('tool_task', 'enablerunnow') && $runnabletasks ) {
                $runnow = html_writer::div(html_writer::link(
                        new moodle_url('/admin/tool/task/schedule_task.php',
                            array('task' => get_class($task))),
                        get_string('runnow', 'tool_task')), 'task-runnow');
            }

            $clearfail = '';
            if ($task->get_fail_delay()) {
                $clearfail = html_writer::div(html_writer::link(
                        new moodle_url('/admin/tool/task/clear_fail_delay.php',
                                array('task' => get_class($task), 'sesskey' => sesskey())),
                        get_string('clear')), 'task-clearfaildelay');
            }

            $row = new html_table_row(array(
                        $namecell,
                        $componentcell,
                        new html_table_cell($editlink),
                        new html_table_cell($loglink),
                        new html_table_cell($lastrun . $runnow),
                        new html_table_cell($nextrun),
                        new html_table_cell($task->get_minute()),
                        new html_table_cell($task->get_hour()),
                        new html_table_cell($task->get_day()),
                        new html_table_cell($task->get_day_of_week()),
                        new html_table_cell($task->get_month()),
                        new html_table_cell($task->get_fail_delay() . $clearfail),
                        new html_table_cell($customised)));

            // Cron-style values must always be LTR.
            $row->cells[6]->attributes['class'] = 'text-ltr';
            $row->cells[7]->attributes['class'] = 'text-ltr';
            $row->cells[8]->attributes['class'] = 'text-ltr';
            $row->cells[9]->attributes['class'] = 'text-ltr';
            $row->cells[10]->attributes['class'] = 'text-ltr';

            if ($disabled) {
                $row->attributes['class'] = 'disabled';
            }
            $data[] = $row;
        }
        $table->data = $data;
        return html_writer::table($table);
    }
77500
public static function main($task)
    {
        $methodName = "main";
        $dispatchable = null;
        try {
            if ($task instanceof Dispatchable) {
                $dispatchable = $task;
            } elseif ($task instanceof UnknownElement) {
                $ue = $task;
                $realThing = $ue->getRealThing();
                if ($realThing != null && $realThing instanceof Dispatchable && $realThing instanceof Task) {
                    $dispatchable = $realThing;
                }
            }
            if ($dispatchable != null) {
                $mName = null;

                $name = trim($dispatchable->getActionParameterName());
                if (empty($name)) {
                    throw new BuildException(
                        "Action Parameter Name must not be empty for Dispatchable Task."
                    );
                }
                $mName = "get" . ucfirst($name);
                try {
                    $c = new ReflectionClass($dispatchable);
                    $actionM = $c->getMethod($mName);
                    $o = $actionM->invoke($dispatchable);
                    $methodName = trim((string) $o);
                    if (empty($methodName)) {
                        throw new ReflectionException();
                    }
                } catch (ReflectionException $re) {
                    throw new BuildException(
                        "Dispatchable Task attribute '" . $name . "' not set or value is empty."
                    );
                }
                $executeM = $c->getMethod($methodName);
                $executeM->invoke($dispatchable);

                if ($task instanceof UnknownElement) {
                    $task->setRealThing(null);
                }
            } else {
                try {
                    $refl = new ReflectionClass($task);
                    $executeM = $refl->getMethod($methodName);
                } catch (ReflectionException $re) {
                    throw new BuildException("No public " . $methodName . "() in " . get_class($task));
                }
                $executeM->invoke($task);
                if ($task instanceof UnknownElement) {
                    $task->setRealThing(null);
                }
            }
        } catch (ReflectionException $e) {
            throw new BuildException($e);
        }
    }