Parse an existing crontab

@param Crontab $crontab

@return CrontabFileHandler
19277
public function parseExistingCrontab(Crontab $crontab)
    {

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

        return $this;
    }
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);
    }
269058
protected static function parseCommand()
    {
        global $argv;
        // Check argv;
        $start_file = $argv[0];
        if (!isset($argv[1])) {
            exit("Usage: php yourfile.php {start|stop|restart|reload|status}\n");
        }

        // Get command.
        $command  = trim($argv[1]);
        $command2 = isset($argv[2]) ? $argv[2] : '';

        // Start command.
        $mode = '';
        if ($command === 'start') {
            if ($command2 === '-d' || Worker::$daemonize) {
                $mode = 'in DAEMON mode';
            } else {
                $mode = 'in DEBUG mode';
            }
        }
        self::log("Workerman[$start_file] $command $mode");

        // Get master process PID.
        $master_pid      = is_file(self::$pidFile) ? file_get_contents(self::$pidFile) : 0;
        $master_is_alive = $master_pid && @swoole_process::kill($master_pid, 0);
        // Master is still alive?
        if ($master_is_alive) {
            if ($command === 'start' && getmypid() != $master_pid) {
                self::log("Workerman[$start_file] already running");
                exit;
            }
        } elseif ($command !== 'start' && $command !== 'restart') {
            self::log("Workerman[$start_file] not run");
            exit;
        }

        // execute command.
        switch ($command) {
            case 'start':
                if ($command2 === '-d') {
                    Worker::$daemonize = true;
                }
                break;
            case 'status':
                if (is_file(self::$_statisticsFile)) {
                    @unlink(self::$_statisticsFile);
                }
                // Master process will send status signal to all child processes.
                swoole_process::kill($master_pid, SIGUSR2);
                // Waiting amoment.
                usleep(500000);
                // Display statisitcs data from a disk file.
                @readfile(self::$_statisticsFile);
                exit(0);
            case 'restart':
            case 'stop':
                self::log("Workerman[$start_file] is stoping ...");
                // Send stop signal to master process.
                $master_pid && swoole_process::kill($master_pid, SIGINT);
                // Timeout.
                $timeout    = 5;
                $start_time = time();
                // Check master process is still alive?
                while (1) {
                    $master_is_alive = $master_pid && swoole_process::kill($master_pid, 0);
                    if ($master_is_alive) {
                        // Timeout?
                        if (time() - $start_time >= $timeout) {
                            self::log("Workerman[$start_file] stop fail");
                            exit;
                        }
                        // Waiting amoment.
                        usleep(10000);
                        continue;
                    }
                    // Stop success.
                    self::log("Workerman[$start_file] stop success");
                    if ($command === 'stop') {
                        exit(0);
                    }
                    if ($command2 === '-d') {
                        Worker::$daemonize = true;
                    }
                    break;
                }
                break;
            case 'reload':
                swoole_process::kill($master_pid, SIGUSR1);
                self::log("Workerman[$start_file] reload");
                exit;
            default :
                exit("Usage: php yourfile.php {start|stop|restart|reload|status}\n");
        }
    }
882226
protected function cron_execute() {

        try {
            $this->restore_response();
            $previous = $this->recentresponse;
            $this->fetch();
            $this->restore_response(true);
            $current = $this->recentresponse;
            $changes = $this->compare_responses($previous, $current);
            $notifications = $this->cron_notifications($changes);
            $this->cron_notify($notifications);
            $this->cron_mtrace('done');
        } catch (checker_exception $e) {
            $this->cron_mtrace('FAILED!');
        }
    }
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);
            }
        }
    }
124920
public function list() : String
    {
        $list = '';

        if( is_file($this->crontabCommands) )
        {
            $jobs  = $this->listArray();
            $list  = '<pre>';
            $list .= '[ID] CRON JOB<br><br>';

            foreach( $jobs as $key => $job )
            {
                $list .= '[' . $key . ']: '. $job . '<br>';
            }

            $list .= '</pre>';
        }

        return $list;
    }
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.');
        }
    }
929413
private function get_cron_data( $name ) {
            $this->_logger->entrance( $name );

            /**
             * @var object $cron_data
             */
            return $this->_storage->get( "{$name}_cron", null );
        }
862952
def setup(cls, cron_cfg="cron"):
        
        random.seed()
        logging_cfg = cls.LOGGING_CFG
        if "%s" in logging_cfg:
            logging_cfg = logging_cfg % (cron_cfg if "--cron" in sys.argv[1:] else "scripts",)
        logging_cfg = os.path.expanduser(logging_cfg)

        if os.path.exists(logging_cfg):
            logging.HERE = os.path.dirname(logging_cfg)
            logging.config.fileConfig(logging_cfg)
        else:
            logging.basicConfig(level=logging.INFO)

        logging.getLogger().debug("Logging config read from '%s'" % logging_cfg)
506025
func NewCrontab(args string, handlers ...Handler) (Crontab, error) {
	return buildCronab(args, handlers...)
}
886853
public static function updateCrontab($sourceFilename, $backupDir = null)
    {
        if (empty($sourceFilename)) {
            throw new \InvalidArgumentException('Invalid argument $srcFilename, must be not empty');
        }

        if (!FileHelper::fileExists($sourceFilename)) {
            throw new \RuntimeException(
                sprintf(
                    'File crontab_filename:"%s" not found',
                    $sourceFilename
                )
            );
        }
        $backupDir = $backupDir ?: '{{deploy_path}}/backup/crontab';

        if (!FileHelper::dirExists($backupDir)) {
            run('mkdir -p '.$backupDir);
            !isVerbose() ?: writeln(sprintf('Backup dir "%s" created', $backupDir));
        }

        $backupFilename = sprintf('%s/crontab.%s', $backupDir, date('Y-m-d_H:i:s'));
        if ((bool)run('if crontab -l > /dev/null 2>&1; then echo 1; else echo 0; fi')) {
            run(sprintf('crontab -l > %s', $backupFilename));
        } else {
            run(sprintf('touch %s', $backupFilename));
        }

        $diff = (bool)run(
            sprintf('if ! diff -q %s %s > /dev/null 2>&1; then echo 1; fi', $backupFilename, $sourceFilename)
        );

        $result = false;
        if ($diff) {
            run(sprintf('crontab "%s"', $sourceFilename));
            !isVerbose() ?: writeln(run('crontab -l'));

            $result = true;
        } else {
            !isVerbose() ?: writeln('Crontab has no diff');
            run('rm '.$backupFilename);
        }

        return $result;
    }
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();
    }
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);
        }

    }
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;
    }
259527
def build_crontab(host)
      # You have been warned..
      crontab = "#\n"
      crontab += "# This file was automatically generated by minicron at #{Time.now.utc}, DO NOT EDIT manually!\n"
      crontab += "#\n\n"

      # Set the path to something sensible by default, eventually this should be configurable
      crontab += "# ENV variables\n"
      crontab += "PATH=#{PATH}\n"
      crontab += "MAILTO=\"\"\n"
      crontab += "\n"

      # Add an entry to the crontab for each job schedule
      unless host.nil?
        host.jobs.each do |job|
          crontab += "# ID:   #{job.id}\n"
          crontab += "# Name: #{job.name}\n"
          crontab += "# Status: #{job.status}\n"

          if !job.schedules.empty?
            job.schedules.each do |schedule|
              crontab += "\t"
              crontab += '# ' unless job.enabled # comment out schedule if job isn't enabled
              crontab += "#{build_minicron_command(schedule.formatted, job.command)}\n"
            end
          else
            crontab += "\t# No schedules exist for this job\n"
          end

          crontab += "\n"
        end
      end

      crontab
    end
503878
def build_crontab_output(opts)
      chdir = Makesure.chdir || File.dirname(Makesure.makesurefile)
      crontab = ""
      crontab << "# Autogenerated by makesure: you probably don't want to edit this file\n\n"
      crontab << "# Cron environment\n"
      crontab << (Makesure.cron_env || "#   customize this by setting Makesure.cron_env in your Makesurefile")
      crontab << "\n"
      Makesure.systems.each do |s|
        uid = s.uid || Makesure.uid
        crontab << "\n"
        crontab << "## Tasks for '#{s.name}'\n"
        crontab << "# Commands\n"
        s.cmds.each do |c|
          crontab << "#{c.cron}\t"
          crontab << "#{uid} " if uid
          crontab << "cd #{chdir} && "

          cmd = "makesure-runner run #{c.command.inspect}"
          crontab << if (opts[:rvm])
            "/bin/bash -l -c '#{cmd}'"
          else
            cmd
          end
          crontab << "\n"
        end

        crontab << "# Verification\n"
        s.verifies.each do |v|
          crontab << "#{v.cron}\t"
          crontab << "#{uid} " if uid
          crontab << "cd #{chdir} && "

          cmd = "makesure-runner verify #{s.name} #{v.name}"
          crontab << if (opts[:rvm])
            "/bin/bash -l -c '#{cmd}'"
          else
            cmd
          end
          crontab << "\n"
        end
        # TODO summarizes
      end
      crontab
    end
986527
def build_command(self):
        """"""
        return cron_utils.cronify("crontab -l | {{ cat; echo \"{} {} {} {} {} CJOBID='{}' MAILTO='' {}\"; }} | crontab - > /dev/null".format(self._minute, self._hour, self._day_of_month, self._month_of_year, self._day_of_week, self._jobid, self._command))