检查crontab格式是否支持
@param  string $cronstr
@return boolean true|false
512072
public static function check($cronstr, $checkCount = true)
    {
        $cronstr = trim($cronstr);

        $splitTags = preg_split('#\s+#', $cronstr);

        if ($checkCount && count($splitTags) !== 5) {
            return false;
        }

        foreach ($splitTags as $tag) {
            $r = '#^\*(\/\d+)?|\d+([\-\/]\d+(\/\d+)?)?(,\d+([\-\/]\d+(\/\d+)?)?)*$#';
            if (preg_match($r, $tag) == false) {
                return false;
            }
        }

        return true;
    }
877241
function () {
        const crons = _.get(Shared, 'runtimeArgs.cron') || _.get(Shared, 'runtimeArgs.crons');
        if (crons) {
            const cronTasks = crons.replace(/\s/g, '').split(',');
            return cronTasks.length > 0 ? cronTasks : undefined;
        }
        return undefined;
    }
1198988
public function isDue()
    {
        $expression = $this->getExpression();
        $cron = CronExpression::factory($expression);
        return $cron->isDue();
    }
1345384
function () {
        const cronJobsToStart = _getNamesOfCronJobsToStart();
        if (!cronJobsToStart && _shouldStartCrons() && Shared.isDbConnectionAvailable() === true) {
            return CronJobManagerJob.startListening().then(function () {
                Logger.tag('Cron').info('Cron Job Manager is started. Starting all available cron jobs');
                return Q();
            }, function (err) {
                Logger.tag('Cron').error('Error starting Cron Job Manager ');
                return Q.reject(err);
            });
        } else if (cronJobsToStart && _shouldStartCrons()) {

            Logger.tag('Cron').info('Starting specific cron jobs "' + cronJobsToStart.join(', ') + '"');

            try {
                const cronJobs = Shared.cronModules(cronJobsToStart);
                let promises = [];
                for (let cron of cronJobs) {
                    // Set force run config
                    cron.forceRun = true;
                    promises.push(cron.worker(cron, cron));
                }
                return Q.all(promises)
                    .then(() => process.exit())
                    .catch(() => process.exit(1));
            } catch (err) {
                process.exit(1);
            }
        } else {
            Logger.tag('Cron').warn('Cron Manager is disabled for this environment.');
            return Q();
        }
    }
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);
            }
        }
    }
364066
public function crontabCallback(Crontab $crontab, LoopInterface $loop)
    {
        $loop->addTimer(60 - time() % 60, function () use ($crontab) {
            $pid = pcntl_fork();
            if ($pid > 0) {
                return;
            } elseif ($pid == 0) {
                $crontab->start(time());
                exit();
            } else {
                $this->logger->error("could not fork");
                exit();
            }
        });
    }
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;
    }
1346863
public function listJobs($crontab){

        $process = new Process($this->crontabCommand($crontab).' -l');
        $process->run();

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

    }
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);
        }

    }
19277
public function parseExistingCrontab(Crontab $crontab)
    {

        foreach ($this->parseString($this->listJobs($crontab)) as $job) {
            $crontab->addJob($job);
        }

        return $this;
    }
1321753
public function parseFromFile(Crontab $crontab, $filename)
    {
        if (!is_readable($filename)) {
            throw new \InvalidArgumentException('File '.$filename.' is not readable.');
        }

        $file = file_get_contents($filename);
        foreach ($this->parseString($file) as $element) {
            $crontab->addItem($element);
        }

        return $this;
    }
1078181
public function init() {
		if ( ! $this->is_enabled() ) {
			return false;
		}

		add_filter( 'cron_schedules', array( $this, 'schedule_cron' ) );
		add_action( $this->id, array( $this, 'cron_worker' ) );

		if ( ! wp_next_scheduled( $this->id ) ) {
			// Schedule health check
			wp_schedule_event( time(), $this->id, $this->id );
		}

		return true;
	}
1270965
protected function _createcronjobs($check = false) {
		$this->out(__d('cake_installer', 'Creating cron jobs'));
		$this->hr();

		$result = true;
		if ($this->InstallerCheck->isOsWindows()) {
			$this->out(__d('cake_installer', 'Server OS is Windows. Creating cron jobs skipped.'));

			return $result;
		}

		$resultCheck = $this->InstallerCheck->checkCronJobsExists();
		if ($resultCheck) {
			if ($check) {
				$this->out('<success>' . __d('cake_installer', 'This action has already been successfully completed. Skipped.') . '</success>');

				return true;
			} elseif ($this->useActionNotify) {
				if (!$this->_checkSure(__d('cake_installer', 'All cron jobs exists. Rewrite?'), 'n')) {
					return true;
				}
			}
		}

		$cronjobsList = $this->ConfigInstaller->getListCronJobsCreation();
		if (empty($cronjobsList)) {
			$this->out('<info>' . __d('cake_installer', 'List of cron jobs is empty') . '</info>');

			return true;
		}

		$apacheUser = $this->InstallerCheck->getWebSrvUser();
		if (empty($apacheUser)) {
			$this->out('<error>' . __d('cake_installer', 'Error on getting the username of the web server process') . '</error>');

			return false;
		}

		$tmpFile = TMP . 'installer' . DS . uniqid('cron_');
		$tmpCrurrFile = TMP . 'installer' . DS . uniqid('cron_');
		$bkpFile = TMP . 'installer' . DS . 'crontab.bkp';
		$output = [];
		$exitCode = -1;
		$cmd = 'crontab -u ' . $apacheUser . ' -l >' . $tmpFile . ' 2>/dev/null';
		exec($cmd, $output, $exitCode);
		if (($exitCode !== 0) && !$this->_createCrontabFile($tmpFile)) {
			$this->out('<error>' . __d('cake_installer', 'Error on getting crontab for user \'%s\'', $apacheUser) . '</error>');

			return false;
		}

		$tailOpt = [
			'ellipsis' => '...',
			'exact' => true,
			'html' => false
		];
		$messages = [];
		$oFileCurr = new File($tmpFile, true);
		if (!$oFileCurr->copy($tmpCrurrFile)) {
			$this->out('<error>' . __d('cake_installer', 'Error on creation copy of current crontab.') . '</error>');
			$oFileCurr->delete();

			return false;
		}
		$oFileBkp = new File($tmpCrurrFile, false);

		$needUpdate = false;
		$cronFile = $oFileCurr->read();
		foreach ($cronjobsList as $cmd => $time) {
			if (empty($cmd) || empty($time)) {
				continue;
			}

			$jobState = false;
			if (!empty($cronFile)) {
				if (preg_match('/^[^#]+' . preg_quote($cmd, '/') . '$/m', $cronFile)) {
					$jobState = true;
				} else {
					$jobState = $oFileCurr->append($time . ' ' . $cmd . "\n");
					$needUpdate = true;
				}
			} else {
				$jobState = $oFileCurr->append($time . ' ' . $cmd . "\n");
				$needUpdate = true;
			}
			if ($jobState) {
				$state = '<success>' . __d('cake_installer', 'Ok') . '</success>';
			} else {
				$state = '<error>' . __d('cake_installer', 'Bad') . '</error>';
				$result = false;
			}

			$state = '[' . $state . ']';
			$message = ' * ' . CakeText::tail($cmd, $this->maxWidth - 12, $tailOpt);
			$messages[] = $this->state->getState($message, $state, $this->maxWidth - 1);
		}
		if (!$oFileCurr->close()) {
			$result = false;
			$messages[] = '<error>' . __d('cake_installer', 'Error on closing cron file.') . '</error>';
		} elseif ($needUpdate) {
			$output = [];
			$exitCode = -1;
			$cmd = 'crontab -u ' . $apacheUser . ' ' . $tmpFile . ' 2>/dev/null';
			exec($cmd, $output, $exitCode);
			if ($exitCode !== 0) {
				$result = false;
				$messages[] = '<error>' . __d('cake_installer', 'Error on updating crontab.') . '</error>';
			} else {
				if (!$oFileBkp->copy($bkpFile, true)) {
					$this->out('<error>' . __d('cake_installer', 'Error on creation copy of previous crontab.') . '</error>');
					$result = false;
				}
			}
		}
		$oFileCurr->delete();
		$oFileBkp->delete();

		if (empty($messages)) {
			$messages[] = '<info>' . __d('cake_installer', 'List of cron jobs is empty') . '</info>';
		} elseif (!$needUpdate) {
			$messages[] = '<info>' . __d('cake_installer', 'Crontab update is not required.') . '</info>';
		}

		$this->out($messages, 1);
		$this->hr();
		if ($result) {
			$this->out('<success>' . __d('cake_installer', 'Creating cron jobs completed successfully.') . '</success>');
		} else {
			$this->out('<error>' . __d('cake_installer', 'Creating cron jobs unsuccessfully.') . '</error>');
		}

		return $result;
	}
814998
public static function get_cron($controller,$action){
        $cron = self::find()->where(['controller'=>$controller,'action'=>$action, 'success' => 0])->orderBy('id_cron_job DESC')->one();
        if (is_null($cron)){
            $cron = new CronJob();
            $cron->controller = $controller;
            $cron->action = $action;
        }
        return $cron;
    }
277031
public function actionStop($index = null)
    {
        /**
         * @var $cron Crontab
         */
        $cron = $this->module->get($this->module->nameComponent);
        if(is_null($index)) {
            $cron->eraseJobs();
        } else {
            $cron->removeJob($index);
        }
        $cron->saveCronFile(); // save to my_crontab cronfile
        $cron->saveToCrontab(); // adds all my_crontab jobs to system (replacing previous my_crontab jobs)
        if($cron->cronGroup){
            echo $this->ansiFormat('Cron Tasks Stopped for group '.$cron->cronGroup .'.'. PHP_EOL, Console::FG_GREEN);
        }else{
            echo $this->ansiFormat('Cron Tasks Stopped.'. PHP_EOL, Console::FG_GREEN);
        }

    }
482815
def _get_cron_cmdstr(path, user=None):
    '''
    
    '''
    if user:
        cmd = 'crontab -u {0}'.format(user)
    else:
        cmd = 'crontab'
    return '{0} {1}'.format(cmd, path)
859464
public function start()
    {
        $this->logger->info("crontab start");

        $loop = Factory::create();

        // add periodic timer
        $crontab_timer = $loop->addPeriodicTimer(60, array($this, 'crontabCallback'));

        // recover the sub processes
        $loop->addPeriodicTimer(60, array($this, 'processRecoverCallback'));

        $server = new \Jenner\Crontab\HTTP\Server($loop, $this, $crontab_timer);
        $server->start($this->port);

        $loop->run();
    }