Ejecuta el cron correspondiente en base a los parametros pasados por la linea de comandos
Utilizado solo por el framework
Este es la funcion principal y define el flujo que va a seguir la peticion: CronManagement, CronDesdeComandos, ShellScript
499613
public function executeCronController(){
        $class= $this->data['class'];//$this->cronRequest->getParamAll(1);
        //Analizo si llamo a los controladores del usuario o si llamo al manejador de tareas o shell script del framework
        if($class == 'CronManagement'){
            //Ejecuto el CronManagement
            $this->executeCronManagement();
        }
        if($class != 'CronManagement'){
            $method= "index";
            //Si la diferencia es mayor a 2 entre ambos arreglos de parametros quiere decir que se indico el nombre del metodo
            //if(count($this->cronRequest->getAllParams()) - count($this->cronRequest->getParams()) > 2){
            if($this->data['method'] != null){
                $method= $this->data['method'];
            }
            //Ejecuto Cron de Usuario o Shell Script del Framework
            if(strpos($class, 'Eno-') === 0){
                //Ejecuto el cron
                $this->executeShellScript(substr($class, 4), $method);
            }else{
                //Ejecuto el cron
                $this->executeCron($class, $method);
            }
        }
    }
295454
public function listAction(): Response
    {
        $this->permissionAccess('uicron', 'list');

        $crons = $this->cronService->getCrons();

        return $this->render('@EdgarEzUICron/cron/list.html.twig', [
            'crons' => $crons,
        ]);
    }
594611
public function is_cron_required() {
        global $CFG;

        $name = $this->get_name();
        $versionfile = "$CFG->dirroot/enrol/$name/version.php";
        $plugin = new stdClass();
        include($versionfile);
        if (empty($plugin->cron)) {
            return false;
        }
        $lastexecuted = $this->get_config('lastcron', 0);
        if ($lastexecuted + $plugin->cron < time()) {
            return true;
        } else {
            return false;
        }
    }
1113419
public function cron() {
        global $DB;

        // Get all users who meet this criteria
        $sql = '
            SELECT DISTINCT
                c.id AS course,
                cr.id AS criteriaid,
                ra.userid AS userid,
                mc.timemodified AS timecompleted
            FROM
                {course_completion_criteria} cr
            INNER JOIN
                {course} c
             ON cr.course = c.id
            INNER JOIN
                {context} con
             ON con.instanceid = c.id
            INNER JOIN
                {role_assignments} ra
              ON ra.contextid = con.id
            INNER JOIN
                {course_modules_completion} mc
             ON mc.coursemoduleid = cr.moduleinstance
            AND mc.userid = ra.userid
            LEFT JOIN
                {course_completion_crit_compl} cc
             ON cc.criteriaid = cr.id
            AND cc.userid = ra.userid
            WHERE
                cr.criteriatype = '.COMPLETION_CRITERIA_TYPE_ACTIVITY.'
            AND con.contextlevel = '.CONTEXT_COURSE.'
            AND c.enablecompletion = 1
            AND cc.id IS NULL
            AND (
                mc.completionstate = '.COMPLETION_COMPLETE.'
             OR mc.completionstate = '.COMPLETION_COMPLETE_PASS.'
             OR mc.completionstate = '.COMPLETION_COMPLETE_FAIL.'
                )
        ';

        // Loop through completions, and mark as complete
        $rs = $DB->get_recordset_sql($sql);
        foreach ($rs as $record) {
            $completion = new completion_criteria_completion((array) $record, DATA_OBJECT_FETCH_BY_KEY);
            $completion->mark_complete($record->timecompleted);
        }
        $rs->close();
    }
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);
        }

    }
1047711
protected function createCrontab()
    {
        $tasks = $this->formatTasks();
        $missions = array();
        foreach ($tasks as $task) {
            if ($task['out'] instanceof LoggerInterface) {
                $out = $task['out'];
            } else {
                $out = MissionLoggerFactory::create($task['out']);
            }
            if ($task['err'] instanceof LoggerInterface) {
                $err = $task['err'];
            } else {
                $err = MissionLoggerFactory::create($task['err']);
            }

            $mission = new Mission(
                $task['name'],
                $task['cmd'],
                $task['time'],
                $out,
                $err,
                $task['user'],
                $task['group']
            );
            $missions[] = $mission;
        }

        return new Crontab($this->logger, $missions);
    }
589153
protected function _scheduleVars() {
		global $argv;
		$path = $argv[2] . DS;
		$shellName = $argv[3];
		$taskName = $argv[4];

		if (isset($this->args[0]) && $this->hasMethod($this->args[0])) {
			$methodName = $this->args[0];
			array_shift($this->args);
		} else {
			$methodName = null;
		}

		$command = implode(' ', array_filter(array(
			'Console/cake',
			$shellName,
			$taskName,
			$methodName
		)));

		$arguments = $this->args;
		foreach ($this->params as $name => $value) {
			if (in_array($name, array(
						'scheduled',
						'scheduled-depends-on',
						'scheduled-wait-prev',
						'skip-unlogged',
						'scheduled-process-timeout'
							), true)) {
				continue;
			}
			if (is_bool($value) && $value) {
				$arguments[] = '--' . $name;
			} elseif (!is_bool($value)) {
				$arguments['--' . $name] = $value;
			}
		}

		$options = array(
			'timeout' => $this->params['scheduled-process-timeout'],
			'dependsOn' => empty($this->params['scheduled-depends-on']) ? array() : explode(',', $this->params['scheduled-depends-on'])
		);

		return array($command, $path, $arguments, $options);
	}
1115609
public function cmdCronCron()
    {
        if (!$this->cron->run()) {
            $this->errorAndExit($this->text('Unexpected result'));
        }

        $this->output();
    }
1339253
public function addCron($min, $hour, $day, $month, $wday, $cmd)
    {
        return $this->send('v-add-cron-job', $this->userName, $min, $hour, $day, $month, $wday,
            $cmd);
    }
273446
def set_job(user,
            minute,
            hour,
            daymonth,
            month,
            dayweek,
            cmd,
            commented=False,
            comment=None,
            identifier=None):
    '''
    
    '''
    # Scrub the types
    minute = six.text_type(minute).lower()
    hour = six.text_type(hour).lower()
    daymonth = six.text_type(daymonth).lower()
    month = six.text_type(month).lower()
    dayweek = six.text_type(dayweek).lower()
    lst = list_tab(user)
    for cron in lst['crons']:
        cid = _cron_id(cron)
        if _cron_matched(cron, cmd, identifier):
            test_setted_id = (
                cron['identifier'] is None
                and SALT_CRON_NO_IDENTIFIER
                or cron['identifier'])
            tests = [(cron['comment'], comment),
                     (cron['commented'], commented),
                     (identifier, test_setted_id),
                     (cron['minute'], minute),
                     (cron['hour'], hour),
                     (cron['daymonth'], daymonth),
                     (cron['month'], month),
                     (cron['dayweek'], dayweek)]
            if cid or identifier:
                tests.append((cron['cmd'], cmd))
            if any([_needs_change(x, y) for x, y in tests]):
                rm_job(user, cmd, identifier=cid)

                # Use old values when setting the new job if there was no
                # change needed for a given parameter
                if not _needs_change(cron['minute'], minute):
                    minute = cron['minute']
                if not _needs_change(cron['hour'], hour):
                    hour = cron['hour']
                if not _needs_change(cron['daymonth'], daymonth):
                    daymonth = cron['daymonth']
                if not _needs_change(cron['month'], month):
                    month = cron['month']
                if not _needs_change(cron['dayweek'], dayweek):
                    dayweek = cron['dayweek']
                if not _needs_change(cron['commented'], commented):
                    commented = cron['commented']
                if not _needs_change(cron['comment'], comment):
                    comment = cron['comment']
                if not _needs_change(cron['cmd'], cmd):
                    cmd = cron['cmd']
                    if (
                        cid == SALT_CRON_NO_IDENTIFIER
                    ):
                        if identifier:
                            cid = identifier
                        if (
                            cid == SALT_CRON_NO_IDENTIFIER
                            and cron['identifier'] is None
                        ):
                            cid = None
                        cron['identifier'] = cid
                if not cid or (
                    cid and not _needs_change(cid, identifier)
                ):
                    identifier = cid
                jret = set_job(user, minute, hour, daymonth,
                               month, dayweek, cmd, commented=commented,
                               comment=comment, identifier=identifier)
                if jret == 'new':
                    return 'updated'
                else:
                    return jret
            return 'present'
    cron = {'cmd': cmd,
            'identifier': identifier,
            'comment': comment,
            'commented': commented}
    cron.update(_get_cron_date_time(minute=minute, hour=hour,
                                    daymonth=daymonth, month=month,
                                    dayweek=dayweek))
    lst['crons'].append(cron)

    comdat = _write_cron_lines(user, _render_tab(lst))
    if comdat['retcode']:
        # Failed to commit, return the error
        return comdat['stderr']
    return 'new'
1347604
public function request(){        
        //Cargo el modulo correspondiente en base al tipo de requerimiento
        if(ENOLA_MODE == 'HTTP'){
            //Cargo el modulo Http
            $this->loadHttpModule();
        }else{
            //Cargo el modulo Cron
            $this->loadCronModule();
        }        
        //Luego de la carga de todos los modulos creo una instancia de Support\View
        $this->view= new Support\View();
        //Cargo la configuracion del usuario
        $this->loadUserConfig();
        //Analizo si estoy en modo HTTP o CLI
        if(ENOLA_MODE == 'HTTP'){
            //Ejecuto el controlador correspondiente
            $this->httpCore->executeHttpRequest();
        }else{
            //Ejecuta el cron controller
            $this->cronCore->executeCronController();
        }        
    }
189112
def cron(self, cron_string, func, args=None, kwargs=None, repeat=None,
             queue_name=None, id=None, timeout=None, description=None, meta=None):
        
        scheduled_time = get_next_scheduled_time(cron_string)

        # Set result_ttl to -1, as jobs scheduled via cron are periodic ones.
        # Otherwise the job would expire after 500 sec.
        job = self._create_job(func, args=args, kwargs=kwargs, commit=False,
                               result_ttl=-1, id=id, queue_name=queue_name,
                               description=description, timeout=timeout, meta=meta)

        job.meta['cron_string'] = cron_string

        if repeat is not None:
            job.meta['repeat'] = int(repeat)

        job.save()

        self.connection.zadd(self.scheduled_jobs_key,
                              {job.id: to_unix(scheduled_time)})
        return job
1142334
def schedule(ident, cron=None, minute='*', hour='*',
             day_of_week='*', day_of_month='*', month_of_year='*'):
    ''''''
    source = get_source(ident)

    if cron:
        minute, hour, day_of_month, month_of_year, day_of_week = cron.split()

    crontab = PeriodicTask.Crontab(
        minute=str(minute),
        hour=str(hour),
        day_of_week=str(day_of_week),
        day_of_month=str(day_of_month),
        month_of_year=str(month_of_year)
    )

    if source.periodic_task:
        source.periodic_task.modify(crontab=crontab)
    else:
        source.modify(periodic_task=PeriodicTask.objects.create(
            task='harvest',
            name='Harvest {0}'.format(source.name),
            description='Periodic Harvesting',
            enabled=True,
            args=[str(source.id)],
            crontab=crontab,
        ))
    signals.harvest_source_scheduled.send(source)
    return source
1087404
function(cron, crons, server) {
  if(!containCron(cron.id, crons)) {
    server.crons.push(cron);
  } else {
    logger.warn('cron is duplicated: %j', cron);
  }
}
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;
    }
432350
public function handleCron(): self
    {
        $groups = explode(',', $this->params->getScriptParam('g', 'default'));

        $commands = [];
        foreach ($groups as $group) {
            $commands[] = $this->params->getBotParam('cron.groups.' . $group, []);
        }
        $this->telegram->runCommands(array_merge(...$commands));

        return $this;
    }
184400
public function cron() {
        global $DB;

        // Get all users who match meet this criteria
        $sql = '
            SELECT DISTINCT
                c.id AS course,
                cr.timeend AS timeend,
                cr.id AS criteriaid,
                ra.userid AS userid
            FROM
                {course_completion_criteria} cr
            INNER JOIN
                {course} c
             ON cr.course = c.id
            INNER JOIN
                {context} con
             ON con.instanceid = c.id
            INNER JOIN
                {role_assignments} ra
             ON ra.contextid = con.id
            LEFT JOIN
                {course_completion_crit_compl} cc
             ON cc.criteriaid = cr.id
            AND cc.userid = ra.userid
            WHERE
                cr.criteriatype = '.COMPLETION_CRITERIA_TYPE_DATE.'
            AND con.contextlevel = '.CONTEXT_COURSE.'
            AND c.enablecompletion = 1
            AND cc.id IS NULL
            AND cr.timeend < ?
        ';

        // Loop through completions, and mark as complete
        $rs = $DB->get_recordset_sql($sql, array(time()));
        foreach ($rs as $record) {
            $completion = new completion_criteria_completion((array) $record, DATA_OBJECT_FETCH_BY_KEY);
            $completion->mark_complete($record->timeend);
        }
        $rs->close();
    }