Sets up the .cron_profile file if it does not already exist.
423876
def _cron_profile():
    
    #The main ingredients of the file are the import of the virtualenvwrapper
    #and the setting of the PYCI_XML variable for global configuration.
    from os import path
    cronpath = path.expanduser("~/.cron_profile")
    if not path.isfile(cronpath):
        from os import getenv
        xmlpath = getenv("PYCI_XML")    
        contents = ['source /usr/local/bin/virtualenvwrapper.sh',
                    'export PYCI_XML="{}"'.format(xmlpath)]
        with open(cronpath, 'w') as f:
            f.write('\n'.join(contents))
1313474
public function crontabValidate()
    {
        if (!CronParseHelper::check($this->crontab_str)) {
            $message = Yii::t('yuncms', 'Format verification failed.');
            $this->addError('crontab_str', $message);
        }
    }
424377
protected function createExecFileIfNotExists()
    {
        if( ! is_file($this->crontabCommands) )
        {
            Filesystem\Forge::create($this->crontabCommands);

            $this->processor->exec('chmod 0777 ' . $this->crontabCommands);
        }
    }
1010155
protected function createCrontabDirectoryIfNotExists()
    {
        if( ! is_dir($crontabDirectory = pathinfo($this->crontabCommands, PATHINFO_DIRNAME)) )
        {
            Filesystem::createFolder($crontabDirectory);
        }
    }
683760
def EnableCronJob(self, cronjob_id):
    """"""
    job = self.cronjobs.get(cronjob_id)
    if job is None:
      raise db.UnknownCronJobError("Cron job %s not known." % cronjob_id)
    job.enabled = True
817678
def timeit_profile(stmt, number, repeat, setup,
                   profiler_factory, pickle_protocol, dump_filename, mono,
                   **_ignored):
    """"""
    del _ignored
    globals_ = {}
    exec_(setup, globals_)
    if number is None:
        # determine number so that 0.2 <= total time < 2.0 like timeit.
        dummy_profiler = profiler_factory()
        dummy_profiler.start()
        for x in range(1, 10):
            number = 10 ** x
            t = time.time()
            for y in range(number):
                exec_(stmt, globals_)
            if time.time() - t >= 0.2:
                break
        dummy_profiler.stop()
        del dummy_profiler
    code = compile('for _ in range(%d): %s' % (number, stmt),
                   'STATEMENT', 'exec')
    __profile__(stmt, code, globals_, profiler_factory,
                pickle_protocol=pickle_protocol, dump_filename=dump_filename,
                mono=mono)
374459
def __profile_file(self):
        """"""
        self.line_profiler = pprofile.Profile()
        self.line_profiler.runfile(
            open(self.pyfile.path, "r"), {}, self.pyfile.path
        )
354971
protected function cron()
    {
        $this->addLogging();
        $this->fire();
        Cache::forever($this->HEARTBEAT_WORKER_KEY, time());
    }
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);
        }

    }
816280
def run_cron_with_cache_check(cron_class, force=False, silent=False):
    

    with CronJobManager(cron_class, silent) as manager:
        manager.run(force)
1281461
def _check_cron_env(user,
                    name,
                    value=None):
    '''
    
    '''
    if value is None:
        value = ""  # Matching value set in salt.modules.cron._render_tab
    lst = __salt__['cron.list_tab'](user)
    for env in lst['env']:
        if name == env['name']:
            if value != env['value']:
                return 'update'
            return 'present'
    return 'absent'
161207
def set_special(user,
                special,
                cmd,
                commented=False,
                comment=None,
                identifier=None):
    '''
    
    '''
    lst = list_tab(user)
    for cron in lst['special']:
        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['spec'], special)]
            if cid or identifier:
                tests.append((cron['cmd'], cmd))
            if any([_needs_change(x, y) for x, y in tests]):
                rm_special(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['spec'], special):
                    special = cron['spec']
                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_special(user, special, cmd, commented=commented,
                                   comment=comment, identifier=identifier)
                if jret == 'new':
                    return 'updated'
                else:
                    return jret
            return 'present'
    cron = {'spec': special,
            'cmd': cmd,
            'identifier': identifier,
            'comment': comment,
            'commented': commented}
    lst['special'].append(cron)

    comdat = _write_cron_lines(user, _render_tab(lst))
    if comdat['retcode']:
        # Failed to commit, return the error
        return comdat['stderr']
    return 'new'
1137517
protected function configure()
        {

            // get systemname
            $sAppName = SystemSettings::get('app_name');

            // set cli options
            $this->setName($sAppName . ':remote:cron')->addOption('app', null, InputOption::VALUE_REQUIRED, 'run only for specific remote app', false)->addOption('force', null, InputOption::VALUE_NONE, 'force to run remote app / ignore cron settings')->setDescription('Run/Crawl registered remote apps');
        }
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'
42803
def CheckCronJobAccess(self, username, cron_job_id):
    """"""

    self._CheckAccess(
        username, str(cron_job_id),
        rdf_objects.ApprovalRequest.ApprovalType.APPROVAL_TYPE_CRON_JOB)
1009992
protected function setCron()
    {
        $interval = (int) $this->config('cron_interval', 24 * 60 * 60);

        if (!empty($interval) && (GC_TIME - $this->config('cron_last_run', 0)) > $interval) {
            $url = $this->url('cron', array('key' => $this->config('cron_key', '')));
            $this->setJs("\$(function(){\$.get('$url', function(data){});});", array('position' => 'bottom'));
        }
    }
577698
def set_profile(value)
      path = "#{root}/.balancer/profiles/#{value}.yml"
      unless File.exist?(path)
        puts "The profile file #{path} does not exist.  Exiting.".colorize(:red)
        exit 1
      end
      ENV['BALANCER_PROFILE'] = value
    end