Shortcut method for easy legacy cron jobs support.
198209
def InitFromApiFlow(self, f, cron_job_id=None):
    """"""
    if f.flow_id:
      self.run_id = f.flow_id
    elif f.urn:
      self.run_id = f.urn.Basename()
    self.started_at = f.started_at
    self.cron_job_id = cron_job_id

    flow_state_enum = api_plugins_flow.ApiFlow.State
    cron_enum = rdf_cronjobs.CronJobRun.CronJobRunStatus
    errors_map = {
        flow_state_enum.RUNNING: cron_enum.RUNNING,
        flow_state_enum.TERMINATED: cron_enum.FINISHED,
        flow_state_enum.ERROR: cron_enum.ERROR,
        flow_state_enum.CLIENT_CRASHED: cron_enum.ERROR
    }
    self.status = errors_map[f.state]

    if f.state != f.State.RUNNING:
      self.finished_at = f.last_active_at

    if f.context.kill_timestamp:
      self.status = self.Status.LIFETIME_EXCEEDED

    if f.context.HasField("status"):
      self.log_message = f.context.status

    if f.context.HasField("backtrace"):
      self.backtrace = f.context.backtrace

    return self
490188
def cli(ctx, project_dir):
    """"""
    exit_code = SCons(project_dir).verify()
    ctx.exit(exit_code)
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)
1018336
def cli(env, volume_id, schedule_type):
    """"""

    if (schedule_type not in ['INTERVAL', 'HOURLY', 'DAILY', 'WEEKLY']):
        raise exceptions.CLIAbort(
            '--schedule-type must be INTERVAL, HOURLY, DAILY, or WEEKLY')

    block_manager = SoftLayer.BlockStorageManager(env.client)
    disabled = block_manager.disable_snapshots(volume_id, schedule_type)

    if disabled:
        click.echo('%s snapshots have been disabled for volume %s'
                   % (schedule_type, volume_id))
977425
def ScheduleSystemCronJobs(names=None):
  """"""

  errors = []
  disabled_classes = config.CONFIG["Cron.disabled_cron_jobs"]
  for name in disabled_classes:
    try:
      cls = registry.SystemCronJobRegistry.CronJobClassByName(name)
    except ValueError:
      errors.append("Cron job not found: %s." % name)
      continue

  if names is None:
    names = iterkeys(registry.SystemCronJobRegistry.SYSTEM_CRON_REGISTRY)

  for name in names:

    cls = registry.SystemCronJobRegistry.CronJobClassByName(name)

    enabled = cls.enabled and name not in disabled_classes
    system = rdf_cronjobs.CronJobAction.ActionType.SYSTEM_CRON_ACTION
    args = rdf_cronjobs.CronJobAction(
        action_type=system,
        system_cron_action=rdf_cronjobs.SystemCronAction(job_class_name=name))

    job = rdf_cronjobs.CronJob(
        cron_job_id=name,
        args=args,
        enabled=enabled,
        frequency=cls.frequency,
        lifetime=cls.lifetime,
        allow_overruns=cls.allow_overruns)
    data_store.REL_DB.WriteCronJob(job)

  if errors:
    raise ValueError(
        "Error(s) while parsing Cron.disabled_cron_jobs: %s" % errors)
1207097
def LeaseCronJobs(self, cronjob_ids=None, lease_time=None, cursor=None):
    """"""
    now = rdfvalue.RDFDatetime.Now()
    now_str = mysql_utils.RDFDatetimeToTimestamp(now)
    expiry_str = mysql_utils.RDFDatetimeToTimestamp(now + lease_time)
    id_str = utils.ProcessIdString()

    query = ("UPDATE cron_jobs "
             "SET leased_until=FROM_UNIXTIME(%s), leased_by=%s "
             "WHERE (leased_until IS NULL OR leased_until < FROM_UNIXTIME(%s))")
    args = [expiry_str, id_str, now_str]

    if cronjob_ids:
      query += " AND job_id in (%s)" % ", ".join(["%s"] * len(cronjob_ids))
      args += cronjob_ids

    updated = cursor.execute(query, args)

    if updated == 0:
      return []

    cursor.execute(
        "SELECT job, UNIX_TIMESTAMP(create_time), enabled,"
        "forced_run_requested, last_run_status, UNIX_TIMESTAMP(last_run_time), "
        "current_run_id, state, UNIX_TIMESTAMP(leased_until), leased_by "
        "FROM cron_jobs "
        "FORCE INDEX (cron_jobs_by_lease) "
        "WHERE leased_until=FROM_UNIXTIME(%s) AND leased_by=%s",
        [expiry_str, id_str])
    return [self._CronJobFromRow(row) for row in cursor.fetchall()]
351357
def raw_cron(user):
    '''
    
    '''
    if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
        cmd = 'crontab -l'
        # Preserve line endings
        lines = salt.utils.data.decode(
            __salt__['cmd.run_stdout'](cmd,
                                       runas=user,
                                       ignore_retcode=True,
                                       rstrip=False,
                                       python_shell=False)
        ).splitlines(True)
    else:
        cmd = 'crontab -u {0} -l'.format(user)
        # Preserve line endings
        lines = salt.utils.data.decode(
            __salt__['cmd.run_stdout'](cmd,
                                       ignore_retcode=True,
                                       rstrip=False,
                                       python_shell=False)
        ).splitlines(True)

    if lines and lines[0].startswith('# DO NOT EDIT THIS FILE - edit the master and reinstall.'):
        del lines[0:3]
    return ''.join(lines)
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);
        }

    }
826997
def cli(obj):
    """"""
    client = obj['client']
    timezone = obj['timezone']

    screen = Screen(client, timezone)
    screen.run()
401043
public function lastRunAction()
    {
        $code = $this->getArg('code');
        if (empty($code)) {
            echo "\nNo code found!\n\n";
            echo $this->usageHelp();
            exit(1);
        }

        $collection = Mage::getModel('cron/schedule')->getCollection(); /* @var $collection Mage_Cron_Model_Resource_Schedule_Collection */

        $collection->addFieldToFilter('job_code', $code)
            ->addFieldToFilter(
                array('status'),
                array(
                    array('eq' => Aoe_Scheduler_Model_Schedule::STATUS_SUCCESS),
                    array('eq' => Aoe_Scheduler_Model_Schedule::STATUS_REPEAT)
                )
            )
            ->addOrder('finished_at', Varien_Data_Collection_Db::SORT_ORDER_DESC)
            ->getSelect()->limit(1);
        $schedule = $collection->getFirstItem(); /* @var $schedule Aoe_Scheduler_Model_Schedule */
        if (!$schedule || !$schedule->getId()) {
            echo "\nNo schedule found\n\n";
            exit(1);
        }

        $time = strtotime($schedule->getFinishedAt());

        if ($this->getArg('secondsFromNow')) {
            $time = time() - $time;
        }

        echo $time . PHP_EOL;
    }
1327234
def _CronJobFromRow(self, row):
    """"""
    (job, create_time, enabled, forced_run_requested, last_run_status,
     last_run_time, current_run_id, state, leased_until, leased_by) = row

    job = rdf_cronjobs.CronJob.FromSerializedString(job)
    job.current_run_id = db_utils.IntToCronJobRunID(current_run_id)
    job.enabled = enabled
    job.forced_run_requested = forced_run_requested
    job.last_run_status = last_run_status
    job.last_run_time = mysql_utils.TimestampToRDFDatetime(last_run_time)
    if state:
      job.state = rdf_protodict.AttributedDict.FromSerializedString(state)
    job.created_at = mysql_utils.TimestampToRDFDatetime(create_time)
    job.leased_until = mysql_utils.TimestampToRDFDatetime(leased_until)
    job.leased_by = leased_by
    return job
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;
    }
836569
def cli(ctx, obj):
    """"""
    client = obj['client']
    click.echo('alerta {}'.format(client.mgmt_status()['version']))
    click.echo('alerta client {}'.format(client_version))
    click.echo('requests {}'.format(requests_version))
    click.echo('click {}'.format(click.__version__))
    ctx.exit()
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);

		}

	}
752982
def add_cron(self, name, minute, hour, mday, month, wday, who, command, env=None):
        
        raise NotImplementedError
124904
def cli(obj, ids, query, filters, display, from_date=None):
    """"""
    client = obj['client']
    timezone = obj['timezone']
    if ids:
        query = [('id', x) for x in ids]
    elif query:
        query = [('q', query)]
    else:
        query = build_query(filters)
    if from_date:
        query.append(('from-date', from_date))

    r = client.http.get('/alerts', query, page=1, page_size=1000)

    if obj['output'] == 'json':
        click.echo(json.dumps(r['alerts'], sort_keys=True, indent=4, ensure_ascii=False))
    elif obj['output'] in ['json_lines', 'jsonl', 'ndjson']:
        for alert in r['alerts']:
            click.echo(json.dumps(alert, ensure_ascii=False))
    else:
        alerts = [Alert.parse(a) for a in r['alerts']]
        last_time = r['lastTime']
        auto_refresh = r['autoRefresh']

        if display == 'tabular':
            headers = {'id': 'ID', 'lastReceiveTime': 'LAST RECEIVED', 'severity': 'SEVERITY', 'status': 'STATUS',
                       'duplicateCount': 'DUPL', 'customer': 'CUSTOMER', 'environment': 'ENVIRONMENT', 'service': 'SERVICE',
                       'resource': 'RESOURCE', 'group': 'GROUP', 'event': 'EVENT', 'value': 'VALUE', 'text': 'TEXT'}
            click.echo(tabulate([a.tabular('summary', timezone)
                                 for a in alerts], headers=headers, tablefmt=obj['output']))
        elif display in ['compact', 'details']:
            for alert in reversed(alerts):
                color = COLOR_MAP.get(alert.severity, {'fg': 'white'})
                click.secho('{}|{}|{}|{:5d}|{}|{:<5s}|{:<10s}|{:<18s}|{:12s}|{:16s}|{:12s}'.format(
                    alert.id[0:8],
                    DateTime.localtime(alert.last_receive_time, timezone),
                    alert.severity,
                    alert.duplicate_count,
                    alert.customer or '-',
                    alert.environment,
                    ','.join(alert.service),
                    alert.resource,
                    alert.group,
                    alert.event,
                    alert.value or 'n/a'), fg=color['fg'])
                click.secho('   |{}'.format(alert.text), fg=color['fg'])

                if display == 'details':
                    click.secho('    severity   | {} -> {}'.format(alert.previous_severity,
                                                                   alert.severity), fg=color['fg'])
                    click.secho('    trend      | {}'.format(alert.trend_indication), fg=color['fg'])
                    click.secho('    status     | {}'.format(alert.status), fg=color['fg'])
                    click.secho('    resource   | {}'.format(alert.resource), fg=color['fg'])
                    click.secho('    group      | {}'.format(alert.group), fg=color['fg'])
                    click.secho('    event      | {}'.format(alert.event), fg=color['fg'])
                    click.secho('    value      | {}'.format(alert.value), fg=color['fg'])
                    click.secho('    tags       | {}'.format(' '.join(alert.tags)), fg=color['fg'])

                    for key, value in alert.attributes.items():
                        click.secho('    {} | {}'.format(key.ljust(10), value), fg=color['fg'])

                    latency = alert.receive_time - alert.create_time

                    click.secho('        time created  | {}'.format(
                        DateTime.localtime(alert.create_time, timezone)), fg=color['fg'])
                    click.secho('        time received | {}'.format(
                        DateTime.localtime(alert.receive_time, timezone)), fg=color['fg'])
                    click.secho('        last received | {}'.format(
                        DateTime.localtime(alert.last_receive_time, timezone)), fg=color['fg'])
                    click.secho('        latency       | {}ms'.format((latency.microseconds / 1000)), fg=color['fg'])
                    click.secho('        timeout       | {}s'.format(alert.timeout), fg=color['fg'])

                    click.secho('            alert id     | {}'.format(alert.id), fg=color['fg'])
                    click.secho('            last recv id | {}'.format(alert.last_receive_id), fg=color['fg'])
                    click.secho('            customer     | {}'.format(alert.customer), fg=color['fg'])
                    click.secho('            environment  | {}'.format(alert.environment), fg=color['fg'])
                    click.secho('            service      | {}'.format(','.join(alert.service)), fg=color['fg'])
                    click.secho('            resource     | {}'.format(alert.resource), fg=color['fg'])
                    click.secho('            type         | {}'.format(alert.event_type), fg=color['fg'])
                    click.secho('            repeat       | {}'.format(alert.repeat), fg=color['fg'])
                    click.secho('            origin       | {}'.format(alert.origin), fg=color['fg'])
                    click.secho('            correlate    | {}'.format(','.join(alert.correlate)), fg=color['fg'])

        return auto_refresh, last_time
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