Schedule a cronjob
189112
def cron(self, cron_string, func, args=None, kwargs=None, repeat=None,
             queue_name=None, id=None, timeout=None, description=None, meta=None):
        
        scheduled_time = get_next_scheduled_time(cron_string)

        # Set result_ttl to -1, as jobs scheduled via cron are periodic ones.
        # Otherwise the job would expire after 500 sec.
        job = self._create_job(func, args=args, kwargs=kwargs, commit=False,
                               result_ttl=-1, id=id, queue_name=queue_name,
                               description=description, timeout=timeout, meta=meta)

        job.meta['cron_string'] = cron_string

        if repeat is not None:
            job.meta['repeat'] = int(repeat)

        job.save()

        self.connection.zadd(self.scheduled_jobs_key,
                              {job.id: to_unix(scheduled_time)})
        return job
16719
def manage_schedule(self, tag, data):
        '''
        
        '''
        func = data.get('func', None)
        name = data.get('name', None)
        schedule = data.get('schedule', None)
        where = data.get('where', None)
        persist = data.get('persist', None)

        funcs = {'delete': ('delete_job', (name, persist)),
                 'add': ('add_job', (schedule, persist)),
                 'modify': ('modify_job',
                            (name, schedule, persist)),
                 'enable': ('enable_schedule', ()),
                 'disable': ('disable_schedule', ()),
                 'enable_job': ('enable_job', (name, persist)),
                 'disable_job': ('disable_job', (name, persist)),
                 'postpone_job': ('postpone_job', (name, data)),
                 'skip_job': ('skip_job', (name, data)),
                 'reload': ('reload', (schedule,)),
                 'list': ('list', (where,)),
                 'save_schedule': ('save_schedule', ()),
                 'get_next_fire_time': ('get_next_fire_time',
                                        (name,))}

        # Call the appropriate schedule function
        try:
            alias, params = funcs.get(func)
            getattr(self.schedule, alias)(*params)
        except TypeError:
            log.error('Function "%s" is unavailable in salt.utils.scheduler',
                      func)
653834
def StartRun(self, wait_for_start_event, signal_event, wait_for_write_event):
    """"""
    # Signal that the cron thread has started. This way the cron scheduler
    # will know that the task is not sitting in a threadpool queue, but is
    # actually executing.
    wait_for_start_event.set()
    # Wait until the cron scheduler acknowledges the run. If it doesn't
    # acknowledge, just return (it means that the cron scheduler considers
    # this task as "not started" and has returned the lease so that another
    # worker can pick it up).
    if not signal_event.wait(TASK_STARTUP_WAIT):
      return

    try:
      logging.info("Processing cron job: %s", self.job.cron_job_id)
      self.run_state.started_at = rdfvalue.RDFDatetime.Now()
      self.run_state.status = "RUNNING"

      data_store.REL_DB.WriteCronJobRun(self.run_state)
      data_store.REL_DB.UpdateCronJob(
          self.job.cron_job_id,
          last_run_time=rdfvalue.RDFDatetime.Now(),
          current_run_id=self.run_state.run_id,
          forced_run_requested=False)
    finally:
      # Notify the cron scheduler that all the DB updates are done. At this
      # point the cron scheduler can safely return this job's lease.
      wait_for_write_event.set()

    try:
      self.Run()
      self.run_state.status = "FINISHED"
    except LifetimeExceededError:
      self.run_state.status = "LIFETIME_EXCEEDED"
      stats_collector_instance.Get().IncrementCounter(
          "cron_job_failure", fields=[self.job.cron_job_id])
    except Exception as e:  # pylint: disable=broad-except
      logging.exception("Cronjob %s failed with an error: %s",
                        self.job.cron_job_id, e)
      stats_collector_instance.Get().IncrementCounter(
          "cron_job_failure", fields=[self.job.cron_job_id])
      self.run_state.status = "ERROR"
      self.run_state.backtrace = str(e)

    finally:
      self.run_state.finished_at = rdfvalue.RDFDatetime.Now()
      elapsed = self.run_state.finished_at - self.run_state.started_at
      stats_collector_instance.Get().RecordEvent(
          "cron_job_latency", elapsed.seconds, fields=[self.job.cron_job_id])
      if self.job.lifetime:
        expiration_time = self.run_state.started_at + self.job.lifetime
        if self.run_state.finished_at > expiration_time:
          self.run_state.status = "LIFETIME_EXCEEDED"
          stats_collector_instance.Get().IncrementCounter(
              "cron_job_timeout", fields=[self.job.cron_job_id])
      data_store.REL_DB.WriteCronJobRun(self.run_state)

    current_job = data_store.REL_DB.ReadCronJob(self.job.cron_job_id)
    # If no other job was started while we were running, update last status
    # information.
    if current_job.current_run_id == self.run_state.run_id:
      data_store.REL_DB.UpdateCronJob(
          self.job.cron_job_id,
          current_run_id=None,
          last_run_status=self.run_state.status)
565979
public function cronLockAction()
    {
        // Switch lock
        $this->util->getCronJobLock()->reverse();

        // Redirect
        $request = $this->getRequest();
        $this->_reroute($this->menu->getCurrentParent()->toRouteUrl());
    }
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
192881
function(cronspec, sixth) {
    var schedule = later.parse.cron(cronspec, sixth);
    return scheduleToSentence(schedule['schedules'][0], sixth);
  }
740616
def _IsCronJobFailing(self, cron_job):
    """"""
    status = cron_job.Get(cron_job.Schema.LAST_RUN_STATUS)
    if status is None:
      return False

    return status.status != rdf_cronjobs.CronJobRunStatus.Status.OK
1324902
def DeleteCronJob(self, cronjob_id):
    """"""
    if cronjob_id not in self.cronjobs:
      raise db.UnknownCronJobError("Cron job %s not known." % cronjob_id)
    del self.cronjobs[cronjob_id]
    try:
      del self.cronjob_leases[cronjob_id]
    except KeyError:
      pass
    for job_run in self.ReadCronJobRuns(cronjob_id):
      del self.cronjob_runs[(cronjob_id, job_run.run_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)
860323
def schedule_next_requests(self):
        """"""
        # TODO: While there is capacity, schedule a batch of redis requests.
        for req in self.next_requests():
            self.crawler.engine.crawl(req, spider=self)
162115
def schedule_now(self, job):
        
        now = long(self._now() * 1e6)
        self.schedule(job, now)
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)
734109
def schedule(self, task):
        """"""
        self.task_manager.register(task)
        self.worker_manager.dispatch(task)
952407
function(id, period, callback) {
    var self = this;

    if (this.$resource.cron) {
      if (!this.crons[id]) {
        self._logger.call(self, 'POD:Registering Cron:' + self.getName() + ':' + id);
        self.crons[id] = new self.$resource.cron.CronJob(
          period,
          callback,
          null,
          true,
          self.options.timezone
        );
      }
    }
  }
113761
def WriteCronJobRun(self, run_object):
    """"""
    if run_object.cron_job_id not in self.cronjobs:
      raise db.UnknownCronJobError("Job with id %s not found." %
                                   run_object.cron_job_id)

    clone = run_object.Copy()
    clone.timestamp = rdfvalue.RDFDatetime.Now()
    self.cronjob_runs[(clone.cron_job_id, clone.run_id)] = clone
474222
def reload(self, schedule):
        '''
        
        '''
        # Remove all jobs from self.intervals
        self.intervals = {}

        if 'schedule' in schedule:
            schedule = schedule['schedule']
        self.opts.setdefault('schedule', {}).update(schedule)
1181114
def add_cron(self, name, command, minute="*", hour="*", mday="*", month="*", wday="*", who="root", env=None):
        
        if minute == 'random':
            minute = str(random.randrange(60))
        if hour == 'random':
            hour = str(random.randrange(24))
        fp = open('/etc/cron.d/%s' % name, "w")
        if env:
            for key, value in env.items():
                fp.write('%s=%s\n' % (key, value))
        fp.write('%s %s %s %s %s %s %s\n' % (minute, hour, mday, month, wday, who, command))
        fp.close()