Parse an existing crontab

@param Crontab $crontab

@return CrontabFileHandler
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;
    }
265154
public function serve( $service = false )
	{
		$lastminute	= $service ? date( "i", time() ) : "-1";
		do
		{
			if( $lastminute	!= date( "i", time() ) )
			{
				$cp	= new CLI_Server_Cron_Parser( $this->cronTab );
				$jobs	= $cp->getJobs();
				foreach( $jobs as $job )
				{
					if( $job->checkMaturity() )
					{
						$content	= $job->execute();
						if( $content )
						{
							$content	= preg_replace( "@((\\r)?\\n)+$@", "", $content );
							$this->logFile->note( $content );
						}
					}
				}
			}
			if( $service )
			{
				$lastminute	= date( "i", time() );
				sleep( 1 );
			}
		}
		while( $service );
	}
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();
    }
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]);
    }
621437
public function index()
    {
        //  Command line only
        $oInput = Factory::service('Input');
        if (Environment::is(Environment::ENV_PROD) && !$oInput::isCli()) {
            header($oInput->server('SERVER_PROTOCOL') . ' 401 Unauthorized');
            echo '<h1>' . lang('unauthorised') . '</h1>';
            exit(401);
        }

        // --------------------------------------------------------------------------

        /**
         * Look for a controller, app version first then the module's cron controllers directory
         */
        $aControllerPaths = [
            NAILS_APP_PATH . 'application/modules/cron/controllers/',
        ];

        $nailsModules = Components::modules();

        foreach ($nailsModules as $oModule) {

            if ($oModule->moduleName === $this->sModuleName) {
                $aControllerPaths[] = $oModule->path . 'cron/controllers/';
                break;
            }
        }

        //  Look for a valid controller
        $sControllerName    = ucfirst($this->sClassName) . '.php';
        $bDidfindController = false;

        foreach ($aControllerPaths as $sPath) {

            $sControllerPath = $sPath . $sControllerName;

            if (is_file($sControllerPath)) {
                $bDidfindController = true;
                break;
            }
        }

        if (!empty($bDidfindController)) {

            //  Load the file and try and execute the method
            require_once $sControllerPath;

            $this->sModuleName = 'Nails\\Cron\\' . ucfirst($this->sModuleName) . '\\' . ucfirst($this->sClassName);

            if (class_exists($this->sModuleName)) {

                //  New instance of the controller
                $oInstance = new $this->sModuleName($this);

                if (is_callable([$oInstance, $this->sMethod])) {

                    //  Begin timing
                    $this->writeLog('Starting job');

                    if (!empty($this->aParams)) {

                        $this->writeLog('Passed parameters');
                        $this->writeLog(print_r($this->aParams, true));
                    }

                    $iStart = microtime(true) * 10000;

                    call_user_func_array([$oInstance, $this->sMethod], $this->aParams);

                    $iEnd      = microtime(true) * 10000;
                    $iDuration = ($iEnd - $iStart) / 10000;
                    $this->writeLog('Finished job');
                    $this->writeLog('Job took ' . number_format($iDuration, 5) . ' seconds');

                } else {

                    $this->writeLog('Cannot call method "' . $this->sMethod . '"');
                }

            } else {

                $this->writeLog(
                    '"' . $this->sModuleName . '" is incorrectly configured; could not find class ' . $this->sModuleName . '  at path ' . $sControllerPath
                );
            }

        } else {

            $this->writeLog(
                '"' . $this->sModuleName . '/' . $this->sClassName . '/' . $this->sMethod . '" is not a valid route.'
            );
        }
    }
593730
public function process()
    {
        $em = $this->getEm();
        $cronRegistry = $this->getCronjobs();
        $pending = $this->getPending();
        $scheduleLifetime = $this->scheduleLifetime * 60; //convert min to sec

        $now = new \DateTime;
        foreach ($pending as $job) {
            $scheduleTime = $job->getScheduleTime();

            if ($scheduleTime > $now) {
                continue;
            }

            try {
                $errorStatus = Mapper\Cronjob::STATUS_ERROR;

                $missedTime = clone $now;
                $timestamp = $missedTime->getTimestamp();
                $timestamp -= $scheduleLifetime;
                $missedTime->setTimestamp($timestamp);

                if ($scheduleTime < $missedTime) {
                    $errorStatus = Mapper\Cronjob::STATUS_MISSED;
                    throw new Exception\RuntimeException(
                        'too late for job'
                    );
                }

                $code = $job->getCode();

                if (!isset($cronRegistry[$code])) {
                    throw new Exception\RuntimeException(sprintf(
                        'job "%s" undefined in cron registry',
                        $code
                    ));
                }

                if (!$this->tryLockJob($job)) {
                    //another cron started this job intermittently. skip.
                    continue;
                }

                //run job now
                $callback = $cronRegistry[$code]['callback'];
                $args = $cronRegistry[$code]['args'];

                $job->setExecuteTime(new \DateTime);
                $em->persist($job);
                $em->flush();

                call_user_func_array($callback, $args);

                $job
                    ->setStatus(Mapper\Cronjob::STATUS_SUCCESS)
                    ->setFinishTime(new \DateTime);

            } catch (\Exception $e) {
                $job
                    ->setStatus($errorStatus)
                    ->setErrorMsg($e->getMessage())
                    ->setStackTrace($e->getTraceAsString());
            }

            $em->persist($job);
            $em->flush();
        }

        return $this;
    }
1152224
public function updateWith(Cron $cron, $key)
    {
        $this->cronManipulator->replace($this->updateContent($cron, $key));
    }
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;
    }
117025
public function actionStart($taskCommand = null )
    {
        /**
         * @var $cron Crontab
         */
        $cron = $this->module->get($this->module->nameComponent);
        $cron->eraseJobs();
        $common_params = $this->module->params;
        if(!empty($this->module->tasks)) {
            if($taskCommand && isset($this->module->tasks[$taskCommand])){

                    $task = $this->module->tasks[$taskCommand];
                    $params = ArrayHelper::merge( ArrayHelper::getValue($task, 'params',[]), $common_params );

                    $cron->addApplicationJob($this->module->phpPath.' '.$this->getYiiPath(), $task['command'],
                        $params,
                        ArrayHelper::getValue($task, 'min'),
                        ArrayHelper::getValue($task, 'hour'),
                        ArrayHelper::getValue($task, 'day'),
                        ArrayHelper::getValue($task, 'month'),
                        ArrayHelper::getValue($task, 'dayofweek'),
                        $this->module->cronGroup //mast be unique for any app on server
                    );

            } else {
                    foreach ($this->module->tasks as $commandName => $task) {

                        $params = ArrayHelper::merge( ArrayHelper::getValue($task, 'params',[]), $common_params );

                        $cron->addApplicationJob($this->module->phpPath.' '.$this->getYiiPath(), $task['command'],
                            $params,
                            ArrayHelper::getValue($task, 'min'),
                            ArrayHelper::getValue($task, 'hour'),
                            ArrayHelper::getValue($task, 'day'),
                            ArrayHelper::getValue($task, 'month'),
                            ArrayHelper::getValue($task, 'dayofweek'),
                            $this->module->cronGroup //mast be unique for any app on server
                        );
                    }
            }

            $cron->saveCronFile(); // save to my_crontab cronfile
            $cron->saveToCrontab(); // adds all my_crontab jobs to system (replacing previous my_crontab jobs)

            echo $this->ansiFormat('Cron Tasks started.' . PHP_EOL, Console::FG_GREEN);
        } else {
            echo $this->ansiFormat('Cron do not have Tasks.' . PHP_EOL, Console::FG_GREEN);
        }
    }
1261852
def poll_crontab(self):
        
        polled_time = self._get_current_time()
        if polled_time.second >= 30:
            self.log.debug('Skip cronjobs in {}'.format(polled_time))
            return
        for job in self._crontab:
            if not job.is_runnable(polled_time):
                continue
            job.do_action(self, polled_time)
1364824
function Cron (pattern, options, fn) {
		var self = this;
		
		// Optional "new" keyword
		if( !(this instanceof Cron) ) {
			return new Cron(pattern, options, fn);
		}

		self.pattern = new CronPattern(pattern);

		self.schedulerDefaults = {
			stopAt:     Infinity,
			maxRuns:    Infinity,
			kill:       false
		};

		// Make options optional
		if( typeof options === "function" ) {
			fn = options;
			options = {};
		}

		// Store and validate options
		self.opts = self.validateOpts(options || {});

		// Determine what to return, default is self
		if( fn === void 0 ) {
			// Normal initialization, return self
			return self;

		} else {
			// Shorthand schedule requested, return job
			return this.schedule(options, fn);

		}

	}
555467
def activate_crontab(self):
        
        self._crontab = []
        if hasattr(self, 'CRONTAB'):
            for crontab_spec in self.CRONTAB:
                args = cronjob.parse_crontab(crontab_spec)
                job = cronjob.CronJob()
                if args['_timer'] == 'datetime':
                    job.set_triggers(args['trigger_format'], args['trigger_time'])
                if args['_timer'] == 'crontab':
                    job.set_crontab(args['crontab'])
                if args['action'].startswith('.'):
                    action_name = args['action'][1:]
                    action_ = getattr(self.__class__, action_name)
                else:
                    action_ = args['action']
                job.set_action(action_, *args['args'])
                self._crontab.append(job)
        self.start_poller(30, self.poll_crontab)
1333191
public static function getTaskCrontabLine($task, $path, $php_bin, $input_file)
    {
        $str = '';
        $comment = $task->getComment();
        if (!empty($comment)) {
            $str .= '#' . $comment . PHP_EOL;
        }
        if (TaskInterface::TASK_STATUS_ACTIVE != $task->getStatus()) {
            $str .= '#';
        }
        list($class, $method, $args) = self::parseCommand($task->getCommand());
        $exec_cmd = $php_bin . ' ' . $input_file . ' ' . $class . ' ' . $method . ' ' . implode(' ', $args);
        $str .= $task->getTime() . ' cd ' . $path . '; ' . $exec_cmd . ' 2>&1 > /dev/null';
        return $str . PHP_EOL;
    }
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();
        }
    }
506025
func NewCrontab(args string, handlers ...Handler) (Crontab, error) {
	return buildCronab(args, handlers...)
}
881639
public static function run_automated_backup($rundirective = self::RUN_ON_SCHEDULE) {
        global $CFG, $DB;

        $status = true;
        $emailpending = false;
        $now = time();
        $config = get_config('backup');

        mtrace("Checking automated backup status",'...');
        $state = backup_cron_automated_helper::get_automated_backup_state($rundirective);
        if ($state === backup_cron_automated_helper::STATE_DISABLED) {
            mtrace('INACTIVE');
            return $state;
        } else if ($state === backup_cron_automated_helper::STATE_RUNNING) {
            mtrace('RUNNING');
            if ($rundirective == self::RUN_IMMEDIATELY) {
                mtrace('Automated backups are already running. If this script is being run by cron this constitues an error. You will need to increase the time between executions within cron.');
            } else {
                mtrace("automated backup are already running. Execution delayed");
            }
            return $state;
        } else {
            mtrace('OK');
        }
        backup_cron_automated_helper::set_state_running();

        mtrace("Getting admin info");
        $admin = get_admin();
        if (!$admin) {
            mtrace("Error: No admin account was found");
            $state = false;
        }

        if ($status) {
            mtrace("Checking courses");
            mtrace("Skipping deleted courses", '...');
            mtrace(sprintf("%d courses", backup_cron_automated_helper::remove_deleted_courses_from_schedule()));
        }

        if ($status) {

            mtrace('Running required automated backups...');
            cron_trace_time_and_memory();

            // This could take a while!
            core_php_time_limit::raise();
            raise_memory_limit(MEMORY_EXTRA);

            $nextstarttime = backup_cron_automated_helper::calculate_next_automated_backup(null, $now);
            $showtime = "undefined";
            if ($nextstarttime > 0) {
                $showtime = date('r', $nextstarttime);
            }

            $rs = $DB->get_recordset('course');
            foreach ($rs as $course) {
                $backupcourse = $DB->get_record('backup_courses', array('courseid' => $course->id));
                if (!$backupcourse) {
                    $backupcourse = new stdClass;
                    $backupcourse->courseid = $course->id;
                    $backupcourse->laststatus = self::BACKUP_STATUS_NOTYETRUN;
                    $DB->insert_record('backup_courses', $backupcourse);
                    $backupcourse = $DB->get_record('backup_courses', array('courseid' => $course->id));
                }

                // The last backup is considered as successful when OK or SKIPPED.
                $lastbackupwassuccessful =  ($backupcourse->laststatus == self::BACKUP_STATUS_SKIPPED ||
                                            $backupcourse->laststatus == self::BACKUP_STATUS_OK) && (
                                            $backupcourse->laststarttime > 0 && $backupcourse->lastendtime > 0);

                // Assume that we are not skipping anything.
                $skipped = false;
                $skippedmessage = '';

                // Check if we are going to be running the backup now.
                $shouldrunnow = (($backupcourse->nextstarttime > 0 && $backupcourse->nextstarttime < $now)
                    || $rundirective == self::RUN_IMMEDIATELY);

                // If config backup_auto_skip_hidden is set to true, skip courses that are not visible.
                if ($shouldrunnow && $config->backup_auto_skip_hidden) {
                    $skipped = ($config->backup_auto_skip_hidden && !$course->visible);
                    $skippedmessage = 'Not visible';
                }

                // If config backup_auto_skip_modif_days is set to true, skip courses
                // that have not been modified since the number of days defined.
                if ($shouldrunnow && !$skipped && $lastbackupwassuccessful && $config->backup_auto_skip_modif_days) {
                    $timenotmodifsincedays = $now - ($config->backup_auto_skip_modif_days * DAYSECS);
                    // Check log if there were any modifications to the course content.
                    $logexists = self::is_course_modified($course->id, $timenotmodifsincedays);
                    $skipped = ($course->timemodified <= $timenotmodifsincedays && !$logexists);
                    $skippedmessage = 'Not modified in the past '.$config->backup_auto_skip_modif_days.' days';
                }

                // If config backup_auto_skip_modif_prev is set to true, skip courses
                // that have not been modified since previous backup.
                if ($shouldrunnow && !$skipped && $lastbackupwassuccessful && $config->backup_auto_skip_modif_prev) {
                    // Check log if there were any modifications to the course content.
                    $logexists = self::is_course_modified($course->id, $backupcourse->laststarttime);
                    $skipped = ($course->timemodified <= $backupcourse->laststarttime && !$logexists);
                    $skippedmessage = 'Not modified since previous backup';
                }

                // Check if the course is not scheduled to run right now.
                if (!$shouldrunnow) {
                    $backupcourse->nextstarttime = $nextstarttime;
                    $DB->update_record('backup_courses', $backupcourse);
                    mtrace('Skipping ' . $course->fullname . ' (Not scheduled for backup until ' . $showtime . ')');
                } else {
                    if ($skipped) { // Must have been skipped for a reason.
                        $backupcourse->laststatus = self::BACKUP_STATUS_SKIPPED;
                        $backupcourse->nextstarttime = $nextstarttime;
                        $DB->update_record('backup_courses', $backupcourse);
                        mtrace('Skipping ' . $course->fullname . ' (' . $skippedmessage . ')');
                        mtrace('Backup of \'' . $course->fullname . '\' is scheduled on ' . $showtime);
                    } else {
                        // Backup every non-skipped courses.
                        mtrace('Backing up '.$course->fullname.'...');

                        // We have to send an email because we have included at least one backup.
                        $emailpending = true;

                        // Only make the backup if laststatus isn't 2-UNFINISHED (uncontrolled error).
                        if ($backupcourse->laststatus != self::BACKUP_STATUS_UNFINISHED) {
                            // Set laststarttime.
                            $starttime = time();

                            $backupcourse->laststarttime = time();
                            $backupcourse->laststatus = self::BACKUP_STATUS_UNFINISHED;
                            $DB->update_record('backup_courses', $backupcourse);

                            $backupcourse->laststatus = self::launch_automated_backup($course, $backupcourse->laststarttime,
                                    $admin->id);
                            $backupcourse->lastendtime = time();
                            $backupcourse->nextstarttime = $nextstarttime;

                            $DB->update_record('backup_courses', $backupcourse);

                            mtrace("complete - next execution: $showtime");
                        }
                    }

                    // Remove excess backups.
                    $removedcount = self::remove_excess_backups($course, $now);
                }
            }
            $rs->close();
        }

        //Send email to admin if necessary
        if ($emailpending) {
            mtrace("Sending email to admin");
            $message = "";

            $count = backup_cron_automated_helper::get_backup_status_array();
            $haserrors = ($count[self::BACKUP_STATUS_ERROR] != 0 || $count[self::BACKUP_STATUS_UNFINISHED] != 0);

            // Build the message text.
            // Summary.
            $message .= get_string('summary') . "\n";
            $message .= "==================================================\n";
            $message .= '  ' . get_string('courses') . ': ' . array_sum($count) . "\n";
            $message .= '  ' . get_string('ok') . ': ' . $count[self::BACKUP_STATUS_OK] . "\n";
            $message .= '  ' . get_string('skipped') . ': ' . $count[self::BACKUP_STATUS_SKIPPED] . "\n";
            $message .= '  ' . get_string('error') . ': ' . $count[self::BACKUP_STATUS_ERROR] . "\n";
            $message .= '  ' . get_string('unfinished') . ': ' . $count[self::BACKUP_STATUS_UNFINISHED] . "\n";
            $message .= '  ' . get_string('warning') . ': ' . $count[self::BACKUP_STATUS_WARNING] . "\n";
            $message .= '  ' . get_string('backupnotyetrun') . ': ' . $count[self::BACKUP_STATUS_NOTYETRUN]."\n\n";

            //Reference
            if ($haserrors) {
                $message .= "  ".get_string('backupfailed')."\n\n";
                $dest_url = "$CFG->wwwroot/report/backups/index.php";
                $message .= "  ".get_string('backuptakealook','',$dest_url)."\n\n";
                //Set message priority
                $admin->priority = 1;
                //Reset unfinished to error
                $DB->set_field('backup_courses','laststatus','0', array('laststatus'=>'2'));
            } else {
                $message .= "  ".get_string('backupfinished')."\n";
            }

            //Build the message subject
            $site = get_site();
            $prefix = format_string($site->shortname, true, array('context' => context_course::instance(SITEID))).": ";
            if ($haserrors) {
                $prefix .= "[".strtoupper(get_string('error'))."] ";
            }
            $subject = $prefix.get_string('automatedbackupstatus', 'backup');

            //Send the message
            $eventdata = new \core\message\message();
            $eventdata->courseid          = SITEID;
            $eventdata->modulename        = 'moodle';
            $eventdata->userfrom          = $admin;
            $eventdata->userto            = $admin;
            $eventdata->subject           = $subject;
            $eventdata->fullmessage       = $message;
            $eventdata->fullmessageformat = FORMAT_PLAIN;
            $eventdata->fullmessagehtml   = '';
            $eventdata->smallmessage      = '';

            $eventdata->component         = 'moodle';
            $eventdata->name         = 'backup';

            message_send($eventdata);
        }

        //Everything is finished stop backup_auto_running
        backup_cron_automated_helper::set_state_running(false);

        mtrace('Automated backups complete.');

        return $status;
    }
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;
    }