Update cron object.

@param EdgarEzCron $cron

@return bool
349283
public function updateCron(EdgarEzCron $cron): bool
    {
        try {
            $this->getEntityManager()->persist($cron);
            $this->getEntityManager()->flush();
        } catch (ORMException $e) {
            return false;
        }

        return true;
    }
1080181
public function cron() {
        global $CFG;

        // Get configs.
        $imsfilelocation = $this->get_config('imsfilelocation');
        $logtolocation = $this->get_config('logtolocation');
        $mailadmins = $this->get_config('mailadmins');
        $prevtime = $this->get_config('prev_time');
        $prevmd5 = $this->get_config('prev_md5');
        $prevpath = $this->get_config('prev_path');

        if (empty($imsfilelocation)) {
            $filename = "$CFG->dataroot/1/imsenterprise-enrol.xml";  // Default location.
        } else {
            $filename = $imsfilelocation;
        }

        $this->logfp = false;
        if (!empty($logtolocation)) {
            $this->logfp = fopen($logtolocation, 'a');
        }

        $this->defaultcategoryid = null;

        $fileisnew = false;
        if ( file_exists($filename) ) {
            core_php_time_limit::raise();
            $starttime = time();

            $this->log_line('----------------------------------------------------------------------');
            $this->log_line("IMS Enterprise enrol cron process launched at " . userdate(time()));
            $this->log_line('Found file '.$filename);
            $this->xmlcache = '';

            $categoryseparator = trim($this->get_config('categoryseparator'));
            $categoryidnumber = $this->get_config('categoryidnumber');

            // Make sure we understand how to map the IMS-E roles to Moodle roles.
            $this->load_role_mappings();
            // Make sure we understand how to map the IMS-E course names to Moodle course names.
            $this->load_course_mappings();

            $md5 = md5_file($filename); // NB We'll write this value back to the database at the end of the cron.
            $filemtime = filemtime($filename);

            // Decide if we want to process the file (based on filepath, modification time, and MD5 hash)
            // This is so we avoid wasting the server's efforts processing a file unnecessarily.
            if ($categoryidnumber && empty($categoryseparator)) {
                $this->log_line('Category idnumber is enabled but category separator is not defined - skipping processing.');
            } else if (empty($prevpath)  || ($filename != $prevpath)) {
                $fileisnew = true;
            } else if (isset($prevtime) && ($filemtime <= $prevtime)) {
                $this->log_line('File modification time is not more recent than last update - skipping processing.');
            } else if (isset($prevmd5) && ($md5 == $prevmd5)) {
                $this->log_line('File MD5 hash is same as on last update - skipping processing.');
            } else {
                $fileisnew = true; // Let's process it!
            }

            if ($fileisnew) {

                // The <properties> tag is allowed to halt processing if we're demanding a matching target.
                $this->continueprocessing = true;

                // Run through the file and process the group/person entries.
                if (($fh = fopen($filename, "r")) != false) {

                    $line = 0;
                    while ((!feof($fh)) && $this->continueprocessing) {

                        $line++;
                        $curline = fgets($fh);
                        $this->xmlcache .= $curline; // Add a line onto the XML cache.

                        while (true) {
                            // If we've got a full tag (i.e. the most recent line has closed the tag) then process-it-and-forget-it.
                            // Must always make sure to remove tags from cache so they don't clog up our memory.
                            if ($tagcontents = $this->full_tag_found_in_cache('group', $curline)) {
                                $this->process_group_tag($tagcontents);
                                $this->remove_tag_from_cache('group');
                            } else if ($tagcontents = $this->full_tag_found_in_cache('person', $curline)) {
                                $this->process_person_tag($tagcontents);
                                $this->remove_tag_from_cache('person');
                            } else if ($tagcontents = $this->full_tag_found_in_cache('membership', $curline)) {
                                $this->process_membership_tag($tagcontents);
                                $this->remove_tag_from_cache('membership');
                            } else if ($tagcontents = $this->full_tag_found_in_cache('comments', $curline)) {
                                $this->remove_tag_from_cache('comments');
                            } else if ($tagcontents = $this->full_tag_found_in_cache('properties', $curline)) {
                                $this->process_properties_tag($tagcontents);
                                $this->remove_tag_from_cache('properties');
                            } else {
                                break;
                            }
                        }
                    }
                    fclose($fh);
                    fix_course_sortorder();
                }

                $timeelapsed = time() - $starttime;
                $this->log_line('Process has completed. Time taken: '.$timeelapsed.' seconds.');

            }

            // These variables are stored so we can compare them against the IMS file, next time round.
            $this->set_config('prev_time', $filemtime);
            $this->set_config('prev_md5',  $md5);
            $this->set_config('prev_path', $filename);

        } else {
            $this->log_line('File not found: '.$filename);
        }

        if (!empty($mailadmins) && $fileisnew) {
            $timeelapsed = isset($timeelapsed) ? $timeelapsed : 0;
            $msg = "An IMS enrolment has been carried out within Moodle.\nTime taken: $timeelapsed seconds.\n\n";
            if (!empty($logtolocation)) {
                if ($this->logfp) {
                    $msg .= "Log data has been written to:\n";
                    $msg .= "$logtolocation\n";
                    $msg .= "(Log file size: ".ceil(filesize($logtolocation) / 1024)."Kb)\n\n";
                } else {
                    $msg .= "The log file appears not to have been successfully written.\n";
                    $msg .= "Check that the file is writeable by the server:\n";
                    $msg .= "$logtolocation\n\n";
                }
            } else {
                $msg .= "Logging is currently not active.";
            }

            $eventdata = new \core\message\message();
            $eventdata->courseid          = SITEID;
            $eventdata->modulename        = 'moodle';
            $eventdata->component         = 'enrol_imsenterprise';
            $eventdata->name              = 'imsenterprise_enrolment';
            $eventdata->userfrom          = get_admin();
            $eventdata->userto            = get_admin();
            $eventdata->subject           = "Moodle IMS Enterprise enrolment notification";
            $eventdata->fullmessage       = $msg;
            $eventdata->fullmessageformat = FORMAT_PLAIN;
            $eventdata->fullmessagehtml   = '';
            $eventdata->smallmessage      = '';
            message_send($eventdata);

            $this->log_line('Notification email sent to administrator.');

        }

        if ($this->logfp) {
            fclose($this->logfp);
        }

    }
1364448
func (c *client) CronUpdate(owner, name, cron string, in *CronPatch) (*Cron, error) {
	out := new(Cron)
	uri := fmt.Sprintf(pathCron, c.addr, owner, name, cron)
	err := c.patch(uri, in, out)
	return out, err
}
1355304
public function calc_cron($cron_string = null)
    {

        if (empty($cron_string)) return false;

        // set the given cronstring
        $this->cron_string = $cron_string;
        // get the curren timestamp
        $this->current_time = strtotime(date('Y-m-d H:i:00', time()));
        $this->calc_time    = strtotime(date('Y-m-d H:i:00', time()));

        $this->next_run      = 0;
        $this->date_next_run = 0;

        // display cleanup
        $this->year        = null;
        $this->cron_month  = null;
        $this->cron_day    = null;
        $this->cron_minute = null;
        $this->cron_hour   = null;

        $count = count($tmp_array = explode(' ', $this->cron_string));

        if (trim($this->cron_string) == '* * * * *' || trim($this->cron_string) == '* * * * * *') {
            $this->next_run      = strtotime('+1 minute', $this->current_time);
            $this->date_next_run = date('Y-m-d H:i:s', $this->next_run);

            // display cleanup
            $this->cron_minute = (strlen($this->cron_minute = date('i', $this->current_time)) < 2) ? "0$this->cron_minute" : $this->cron_minute;
            $this->cron_hour   = (strlen($this->cron_hour = date('h', $this->current_time)) < 2) ? "0$this->cron_hour" : $this->cron_hour;
            $this->cron_day    = (strlen($this->cron_day = date('d', $this->current_time)) < 2) ? "0$this->cron_day" : $this->cron_day;
            $this->cron_month  = (strlen($this->cron_month = date('m', $this->current_time)) < 2) ? "0$this->cron_month" : $this->cron_month;
            $this->cron_year   = (strlen($this->cron_year = date('Y', $this->current_time)) < 2) ? "0$this->cron_hour" : $this->cron_hour;
            $this->cron_array  = array();

            return true;
        }

        // set the cron array
        $this->cron_array = array(
            0 => array(
                'placeholder' => 'i',
                'range'       => array(
                    'range'    => '*',
                    'interval' => false
                ),
                'p_name'      => 'cron_minute'
            ),
            1 => array(
                'placeholder' => 'H',
                'range'       => array(
                    'range'    => '*',
                    'interval' => false
                ),
                'p_name'      => 'cron_hour'
            ),
            2 => array(
                'placeholder' => 'd',
                'range'       => array(
                    'range'    => '*',
                    'interval' => false
                ),
                'p_name'      => 'cron_day'
            ),
            3 => array(
                'placeholder' => 'm',
                'range'       => array(
                    'range'    => '*',
                    'interval' => false
                ),
                'p_name'      => 'cron_month'
            ),
            4 => array(
                'placeholder' => 'w',
                'range'       => array(
                    'range'    => '*',
                    'interval' => false
                ),
                'p_name'      => 'cron_weekday'
            ),
            5 => array(
                'placeholder' => 'Y',
                'range'       => array(
                    'range'    => '*',
                    'interval' => false
                ),
                'p_name'      => 'cron_year'
            )
        );

        // get the time range for the specific year / month
        for ($i = 0; $i < $count; $i++) {
            $this->cron_array[$i]['range'] = $this->parse_position($tmp_array[$i]);
        }

        unset($tmp_array, $i);

        // since the year is optional
        if ($count < 6) {
            $this->cron_array[5]['range'] = $this->parse_position(date('Y'));
            $count++;
        }

        $next_up = false;

        // foreach ( $this->cron_array as $key => $val )
        for ($i = 0; $i < $count; $i++) {
            if (!empty($this->cron_array[$i]['range']) && !is_array($this->cron_array[$i]['range']['range'])) {
                $sub_range = array(
                    'range'       => $this->cron_array[$i]['range']['range'],
                    'interval'    => $this->cron_array[$i]['range']['interval'],
                    'placeholder' => $this->cron_array[$i]['placeholder'],
                    'p_name'      => $this->cron_array[$i]['p_name']
                );

                $this->__set_value($sub_range);
            } else {

                foreach ($this->cron_array[$i]['range'] as $range) {
                    if (!is_array($range)) continue;

                    if ($next_up === true) {
                        $val_string  = (string)substr($this->cron_array[$i]['p_name'], 5);
                        $val         = (string)date($this->cron_array[$i]['placeholder'], strtotime("+1 $val_string", $this->calc_time));
                        $date_string = '';
                        switch ($i) {
                            case 0 :
                                $date_string = (string)"Y-m-d H:$val:00";
                                break;
                            case 1 :
                                $date_string = (string)"Y-m-d $val:00:00";
                                break;
                            case 2 :
                                $date_string = (string)"Y-m-$val 00:00:00";
                                break;
                            case 3 :
                                $date_string = (string)"Y-$val-01 00:00:00";
                                break;
                            case 4 :
                                break;
                            case 5 :
                                $date_string = (string)"$val-01-01 00:00";
                                break;
                            default :
                                $date_string = (string)"Y-m-d H:i:s";
                                break;
                        }
                        // the calcuation date
                        $this->calc_time = (int)strtotime(date((string)$date_string));

                        // reset the restart
                        $next_up = false;

                        for ($x = 0; count($this->cron_array) > $x; $x++) {
                            $this->{$this->cron_array[$x]['p_name']} = null;
                        }
                        // cleanup useless vars
                        unset($x, $val, $val_string, $date_string);
                        // reset to the first field
                        $i = -1;
                        // start from beginning break this loop
                        break;
                    }

                    // go through all subranges
                    foreach ($range as $sub_range) {
                        $sub_range['placeholder'] = (string)$this->cron_array[$i]['placeholder'];
                        $sub_range['p_name']      = (string)$this->cron_array[$i]['p_name'];
                        if (!empty($this->{$this->cron_array[$i]['p_name']})) break;
                        $this->__set_value((array)$sub_range);
                    }

                    // check if a value has been set
                    if (!isset($this->{$this->cron_array[$i]['p_name']})) {
                        $next_up = true;
                    }
                    unset($sub_range);
                }
                unset($range);
            }
        }
        // display cleanup
        $this->cron_minute = (strlen($this->cron_minute) < 2) ? "0$this->cron_minute" : $this->cron_minute;
        $this->cron_hour   = (strlen($this->cron_hour) < 2) ? "0$this->cron_hour" : $this->cron_hour;
        $this->cron_day    = (strlen($this->cron_day) < 2) ? "0$this->cron_day" : $this->cron_day;
        $this->cron_month  = (strlen($this->cron_month) < 2) ? "0$this->cron_month" : $this->cron_month;
        // set the next possible timestamp
        $this->date_next_run = "{$this->cron_year}-{$this->cron_month}-{$this->cron_day} {$this->cron_hour}:{$this->cron_minute}:00";
        $this->next_run      = strtotime($this->date_next_run);

        // clear cron array
        $this->cron_array = array();

        return $this->next_run;
    }
1138630
public function cron($timeLimit = self::CRON_EXEC_TIME, $workerID = self::WORKER_ID)
    {
        $start = microtime(true);
        $workerID = $this->setWorkerID($workerID);
        $log = [];
        $lastCount = -1;
        while (count($log) > $lastCount &&
            (
                empty($timeLimit) ||
                $timeLimit > (microtime(true) - $start)
            )
        ) {
            $lastCount = count($log);
            $query = $this->pdo->prepare(<<<SQL
UPDATE robotstxt__cache1
SET worker = :workerID
WHERE worker IS NULL AND nextUpdate <= UNIX_TIMESTAMP()
ORDER BY nextUpdate ASC
LIMIT 1;
SQL
            );
            $query->bindValue('workerID', $workerID, \PDO::PARAM_INT);
            $query->execute();
            $query = $this->pdo->prepare(<<<SQL
SELECT base
FROM robotstxt__cache1
WHERE worker = :workerID
ORDER BY nextUpdate DESC
LIMIT 10;
SQL
            );
            $query->bindValue('workerID', $workerID, \PDO::PARAM_INT);
            $query->execute();
            while ($baseUri = $query->fetch(\PDO::FETCH_COLUMN)) {
                if ((new Base($this->pdo, $baseUri, $this->curlOptions, $this->byteLimit))->refresh()) {
                    $log[(string)microtime(true)] = $baseUri;
                }
            }
        }
        return $log;
    }
2639
public function parseExistingCrontab(Crontab $crontab)
    {
        // parsing cron file
        $process = new Process($this->crontabCommand($crontab).' -l');
        $process->run();

        foreach ($this->parseString($process->getOutput()) as $item) {
            $crontab->addItem($item);
        }

        $this->error = $process->getErrorOutput();

        return $this;
    }
1241413
public function isDue()
    {
        $cron = App::make('Cron\CronExpression', [$this->scheduler->getCronSchedule()]);

        // if a week is defined, so some special weekly stuff
        if ($this->scheduler->getScheduleWeek() !== Scheduler::NONE) {
            return $this->thisWeek() && $cron->isDue();
        }

        //otherwise us only standard cron scheduling
        return $cron->isDue();
    }
309049
public function editCron($job, $min, $hour, $day, $month, $wday, $cmd)
    {
        return $this->send('v-change-cron-job', $this->userName, $job, $min, $hour, $day, $month,
            $wday, $cmd);
    }
494002
public function validateCronExpression($cronExpression)
    {
        try {
            $schedule = Mage::getModel('cron/schedule');
            /* @var $schedule Mage_Cron_Model_Schedule */
            $schedule->setCronExpr($cronExpression);
        } catch (Exception $e) {
            return false;
        }
        return true;
    }
1100611
protected function cron_notify(array $notifications) {
        global $CFG;

        if (empty($notifications)) {
            $this->cron_mtrace('nothing to notify about. ', '');
            return;
        }

        $admins = get_admins();

        if (empty($admins)) {
            return;
        }

        $this->cron_mtrace('sending notifications ... ', '');

        $text = get_string('updatenotifications', 'core_admin') . PHP_EOL;
        $html = html_writer::tag('h1', get_string('updatenotifications', 'core_admin')) . PHP_EOL;

        $coreupdates = array();
        $pluginupdates = array();

        foreach ($notifications as $notification) {
            if ($notification->component == 'core') {
                $coreupdates[] = $notification;
            } else {
                $pluginupdates[] = $notification;
            }
        }

        if (!empty($coreupdates)) {
            $text .= PHP_EOL . get_string('updateavailable', 'core_admin') . PHP_EOL;
            $html .= html_writer::tag('h2', get_string('updateavailable', 'core_admin')) . PHP_EOL;
            $html .= html_writer::start_tag('ul') . PHP_EOL;
            foreach ($coreupdates as $coreupdate) {
                $html .= html_writer::start_tag('li');
                if (isset($coreupdate->release)) {
                    $text .= get_string('updateavailable_release', 'core_admin', $coreupdate->release);
                    $html .= html_writer::tag('strong', get_string('updateavailable_release', 'core_admin', $coreupdate->release));
                }
                if (isset($coreupdate->version)) {
                    $text .= ' '.get_string('updateavailable_version', 'core_admin', $coreupdate->version);
                    $html .= ' '.get_string('updateavailable_version', 'core_admin', $coreupdate->version);
                }
                if (isset($coreupdate->maturity)) {
                    $text .= ' ('.get_string('maturity'.$coreupdate->maturity, 'core_admin').')';
                    $html .= ' ('.get_string('maturity'.$coreupdate->maturity, 'core_admin').')';
                }
                $text .= PHP_EOL;
                $html .= html_writer::end_tag('li') . PHP_EOL;
            }
            $text .= PHP_EOL;
            $html .= html_writer::end_tag('ul') . PHP_EOL;

            $a = array('url' => $CFG->wwwroot.'/'.$CFG->admin.'/index.php');
            $text .= get_string('updateavailabledetailslink', 'core_admin', $a) . PHP_EOL;
            $a = array('url' => html_writer::link($CFG->wwwroot.'/'.$CFG->admin.'/index.php', $CFG->wwwroot.'/'.$CFG->admin.'/index.php'));
            $html .= html_writer::tag('p', get_string('updateavailabledetailslink', 'core_admin', $a)) . PHP_EOL;

            $text .= PHP_EOL . get_string('updateavailablerecommendation', 'core_admin') . PHP_EOL;
            $html .= html_writer::tag('p', get_string('updateavailablerecommendation', 'core_admin')) . PHP_EOL;
        }

        if (!empty($pluginupdates)) {
            $text .= PHP_EOL . get_string('updateavailableforplugin', 'core_admin') . PHP_EOL;
            $html .= html_writer::tag('h2', get_string('updateavailableforplugin', 'core_admin')) . PHP_EOL;

            $html .= html_writer::start_tag('ul') . PHP_EOL;
            foreach ($pluginupdates as $pluginupdate) {
                $html .= html_writer::start_tag('li');
                $text .= get_string('pluginname', $pluginupdate->component);
                $html .= html_writer::tag('strong', get_string('pluginname', $pluginupdate->component));

                $text .= ' ('.$pluginupdate->component.')';
                $html .= ' ('.$pluginupdate->component.')';

                $text .= ' '.get_string('updateavailable', 'core_plugin', $pluginupdate->version);
                $html .= ' '.get_string('updateavailable', 'core_plugin', $pluginupdate->version);

                $text .= PHP_EOL;
                $html .= html_writer::end_tag('li') . PHP_EOL;
            }
            $text .= PHP_EOL;
            $html .= html_writer::end_tag('ul') . PHP_EOL;

            $a = array('url' => $CFG->wwwroot.'/'.$CFG->admin.'/plugins.php');
            $text .= get_string('updateavailabledetailslink', 'core_admin', $a) . PHP_EOL;
            $a = array('url' => html_writer::link($CFG->wwwroot.'/'.$CFG->admin.'/plugins.php', $CFG->wwwroot.'/'.$CFG->admin.'/plugins.php'));
            $html .= html_writer::tag('p', get_string('updateavailabledetailslink', 'core_admin', $a)) . PHP_EOL;
        }

        $a = array('siteurl' => $CFG->wwwroot);
        $text .= PHP_EOL . get_string('updatenotificationfooter', 'core_admin', $a) . PHP_EOL;
        $a = array('siteurl' => html_writer::link($CFG->wwwroot, $CFG->wwwroot));
        $html .= html_writer::tag('footer', html_writer::tag('p', get_string('updatenotificationfooter', 'core_admin', $a),
            array('style' => 'font-size:smaller; color:#333;')));

        foreach ($admins as $admin) {
            $message = new \core\message\message();
            $message->courseid          = SITEID;
            $message->component         = 'moodle';
            $message->name              = 'availableupdate';
            $message->userfrom          = get_admin();
            $message->userto            = $admin;
            $message->subject           = get_string('updatenotificationsubject', 'core_admin', array('siteurl' => $CFG->wwwroot));
            $message->fullmessage       = $text;
            $message->fullmessageformat = FORMAT_PLAIN;
            $message->fullmessagehtml   = $html;
            $message->smallmessage      = get_string('updatenotifications', 'core_admin');
            $message->notification      = 1;
            message_send($message);
        }
    }
1365998
private function is_cron_on( $name ) {
            $this->_logger->entrance( $name );

            /**
             * @var object $cron_data
             */
            $cron_data = $this->get_cron_data( $name );

            return ( ! is_null( $cron_data ) && true === $cron_data->on );
        }
694130
public function start($id_cron): bool
  {
    $res = false;
    if ( $this->check() && ($cron = $this->get_cron($id_cron)) ){
      bbn\appui\history::disable();
      $start = date('Y-m-d H:i:s');
      if ( $this->db->update($this->table, [
        'prev' => $start,
        'next' => date('Y-m-d H:i:s', $this->get_next_date($cron['cfg']['frequency']))
      ], [
        'id' => $id_cron
      ]) ){
        $res = true;
      }
      bbn\appui\history::enable();
    }
    return $res;
  }
858101
public function cron() {
    // @todo Use config to stop/resume the runner.
    $prefix = 'openy_cron_';
    /** @var OpenyCronServiceInterface $service */
    foreach ($this->cronServices as $periodicity => $services) {
      foreach ($services as $service) {
        $name = $prefix . $service->_serviceId;
        $last_run = $this->state->get($name);
        if ((REQUEST_TIME - $last_run) > $periodicity) {
          // @todo Fix DI on OpenY sprint.
          \Drupal::logger("openy_cron")->info('Service %service has been started.', ['%service' => $service->_serviceId]);
          Timer::start($name);
          $service->runCronServices();
          $execution_time = Timer::read($name) / 1000;
          $this->state->set($name, REQUEST_TIME);
          \Drupal::logger("openy_cron")->info('Service %service has been finished. Execution time: %time sec.', ['%service' => $service->_serviceId, '%time' => $execution_time]);
          Timer::stop($name);
        }
      }
    }
  }
1355453
public function cron()
    {

        //Increase memory and runtime
        ini_set('memory_limit', "512M");
        ini_set('max_execution_time', 60 * 60 * 60);

        //Include required resources
        require_once(ABSPATH . 'wp-admin/includes/user.php');

        //Step 1: Create diffs
        $createAccounts = $this->diffUserAccounts(true);
        $deleteAccounts = $this->diffUserAccounts(false);

        //Sanity check, many users to remove?
        $maxDeleteLimit = isset($_GET['maxDeletelimit']) ? (int) $_GET['maxDeletelimit'] : 100;

        if (count($deleteAccounts) > $maxDeleteLimit) {
            if (is_main_site()) {
                if (get_transient('ad_api_too_many_deletions') !== 1) {

                    //Send mail
                    wp_mail(
                        get_option('admin_email'),
                        "Ad-integration plugin",
                        __("To many user deletions in queue (" . count($deleteAccounts) . "/" . $maxDeleteLimit . ") add https://test.dev/wp-admin/?adbulkimport&maxDeleteLimit=100 to your query to allow number of required deletions.",
                            "adintegration")
                    );

                    //Write to log
                    error_log("Ad-integration plugin: To many user deletions in queue (" . count($deleteAccounts) . "/" . $maxDeleteLimit . ") add https://test.dev/wp-admin/?adbulkimport&maxDeleteLimit=100 to your query to allow number of required deletions.");

                    //Prevent this mail for 24 hours
                    set_transient('ad_api_too_many_deletions', 1, 23 * HOUR_IN_SECONDS);
                }
            }
        } else {
            //Step 2: Delete these accounts
            if (is_array($deleteAccounts) && !empty($deleteAccounts)) {
                foreach ((array)$deleteAccounts as $accountName) {
                    $this->deleteAccount($accountName);
                }
            }
        }

        //Step 3: Create these accounts
        if (is_array($createAccounts) && !empty($createAccounts)) {
            foreach ((array)$createAccounts as $accountName) {
                if (!in_array($accountName, $deleteAccounts)) {
                    $this->createAccount($accountName);
                }
            }
        }

        //Step 4: Schedule profile updates
        $this->scheduleUpdateProfiles();
    }
578986
public function cron() {
        global $CFG, $DB;
        require_once($CFG->libdir.'/cronlib.php');

        // find out all stale draft areas (older than 4 days) and purge them
        // those are identified by time stamp of the /. root dir
        mtrace('Deleting old draft files... ', '');
        cron_trace_time_and_memory();
        $old = time() - 60*60*24*4;
        $sql = "SELECT *
                  FROM {files}
                 WHERE component = 'user' AND filearea = 'draft' AND filepath = '/' AND filename = '.'
                       AND timecreated < :old";
        $rs = $DB->get_recordset_sql($sql, array('old'=>$old));
        foreach ($rs as $dir) {
            $this->delete_area_files($dir->contextid, $dir->component, $dir->filearea, $dir->itemid);
        }
        $rs->close();
        mtrace('done.');

        // remove orphaned preview files (that is files in the core preview filearea without
        // the existing original file)
        mtrace('Deleting orphaned preview files... ', '');
        cron_trace_time_and_memory();
        $sql = "SELECT p.*
                  FROM {files} p
             LEFT JOIN {files} o ON (p.filename = o.contenthash)
                 WHERE p.contextid = ? AND p.component = 'core' AND p.filearea = 'preview' AND p.itemid = 0
                       AND o.id IS NULL";
        $syscontext = context_system::instance();
        $rs = $DB->get_recordset_sql($sql, array($syscontext->id));
        foreach ($rs as $orphan) {
            $file = $this->get_file_instance($orphan);
            if (!$file->is_directory()) {
                $file->delete();
            }
        }
        $rs->close();
        mtrace('done.');

        // Remove orphaned converted files (that is files in the core documentconversion filearea without
        // the existing original file).
        mtrace('Deleting orphaned document conversion files... ', '');
        cron_trace_time_and_memory();
        $sql = "SELECT p.*
                  FROM {files} p
             LEFT JOIN {files} o ON (p.filename = o.contenthash)
                 WHERE p.contextid = ? AND p.component = 'core' AND p.filearea = 'documentconversion' AND p.itemid = 0
                       AND o.id IS NULL";
        $syscontext = context_system::instance();
        $rs = $DB->get_recordset_sql($sql, array($syscontext->id));
        foreach ($rs as $orphan) {
            $file = $this->get_file_instance($orphan);
            if (!$file->is_directory()) {
                $file->delete();
            }
        }
        $rs->close();
        mtrace('done.');

        // remove trash pool files once a day
        // if you want to disable purging of trash put $CFG->fileslastcleanup=time(); into config.php
        if (empty($CFG->fileslastcleanup) or $CFG->fileslastcleanup < time() - 60*60*24) {
            require_once($CFG->libdir.'/filelib.php');
            // Delete files that are associated with a context that no longer exists.
            mtrace('Cleaning up files from deleted contexts... ', '');
            cron_trace_time_and_memory();
            $sql = "SELECT DISTINCT f.contextid
                    FROM {files} f
                    LEFT OUTER JOIN {context} c ON f.contextid = c.id
                    WHERE c.id IS NULL";
            $rs = $DB->get_recordset_sql($sql);
            if ($rs->valid()) {
                $fs = get_file_storage();
                foreach ($rs as $ctx) {
                    $fs->delete_area_files($ctx->contextid);
                }
            }
            $rs->close();
            mtrace('done.');

            mtrace('Call filesystem cron tasks.', '');
            cron_trace_time_and_memory();
            $this->filesystem->cron();
            mtrace('done.');
        }
    }
516913
public function run()
    {
        // check if cron instances is defined
        if (!isset($this->configs['instances']) || !Any::isArray($this->configs['instances'])) {
            return null;
        }

        // get timestamp
        $time = time();
        $log = [];

        // each every one instance
        foreach ($this->configs['instances'] as $callback => $delay) {
            if (((int)$this->configs['log'][$callback] + $delay) <= $time) {
                // prepare cron initializing
                list($class, $method) = explode('::', $callback);
                if (class_exists($class) && method_exists($class, $method)) {
                    // make static callback
                    forward_static_call([$class, $method]);
                    $log[] = $callback;
                }
                // update log information
                $this->configs['log'][$callback] = $time + $delay;
            }
        }

        // write updated configs
        App::$Properties->writeConfig('Cron', $this->configs);
        return $log;
    }
521070
private function updateCron(string $id, string $cron)
    {
        $cronExpression = CronExpression::factory($cron);
        $next_run = $cronExpression->getNextRunDate()->getTimestamp();

        $this->client->zadd(self::CRON_QUEUE_NAME, [$id => $next_run]);
    }