Determines if the given job is due for another run.

    Args:
      job: The cron job rdfvalue object.

    Returns:
      True if it is time to run based on the specified frequency.
975312
def JobDueToRun(self, job):
    
    if not job.enabled:
      return False

    if job.forced_run_requested:
      return True

    now = rdfvalue.RDFDatetime.Now()

    if (job.last_run_time is not None and
        job.last_run_time + job.frequency > now):
      return False

    # No currently executing job - lets go.
    if not job.current_run_id:
      return True

    # There is a job executing but we allow overruns.
    if job.allow_overruns:
      return True

    return False
664333
def schedule(self, scheduled_time, func, args=None, kwargs=None,
                 interval=None, repeat=None, result_ttl=None, ttl=None,
                 timeout=None, id=None, description=None, queue_name=None,
                 meta=None):
        
        # Set result_ttl to -1 for periodic jobs, if result_ttl not specified
        if interval is not None and result_ttl is None:
            result_ttl = -1
        job = self._create_job(func, args=args, kwargs=kwargs, commit=False,
                               result_ttl=result_ttl, ttl=ttl, id=id,
                               description=description, queue_name=queue_name,
                               timeout=timeout, meta=meta)

        if interval is not None:
            job.meta['interval'] = int(interval)
        if repeat is not None:
            job.meta['repeat'] = int(repeat)
        if repeat and interval is None:
            raise ValueError("Can't repeat a job without interval argument")
        job.save()
        self.connection.zadd(self.scheduled_jobs_key,
                              {job.id: to_unix(scheduled_time)})
        return job
166480
def run(self):
        
        while not self.stopped:
            now = datetime.utcnow()
            for job in self.parent.jobs:
                if not job.next_run:
                    continue
                if job.next_run >= self.last_check and job.next_run <= now:
                    if job.state.allow_start:
                        job.start()
                    else:
                        job.next_run = job.cron_iter.get_next(datetime)
            self.last_checked = now
            time.sleep(1)
994797
def is_job_done(job_id, conn=None):
    
    result = False
    get_done = RBJ.get_all(DONE, index=STATUS_FIELD)
    for item in get_done.filter({ID_FIELD: job_id}).run(conn):
        result = item
    return result
260620
public synchronized boolean delete(final Job job) {
        // if already shutdown in the process of shutdown, there is no
        // need to remove Jobs as they will never be executed.
        if (shutdown) {
            return false;
        }
        int i = findIndex(job);
        if (i != -1) {
            ScheduledJobEntry se = (ScheduledJobEntry) jobList.remove(i);
            if (se.job != job) { // this should never happen
                new IllegalStateException("Internal programming error");
            }
            // if the job is the first on the list,
            // then notify the scheduler thread to schedule a new job
            if (i == 0) {
                this.notifyAll();
            }
            return true;
        } else {
            return false;
        }
    }
162115
def schedule_now(self, job):
        
        now = long(self._now() * 1e6)
        self.schedule(job, now)
780470
def run(self, schedule_type, lookup_id, **kwargs):
        
        log = self.get_logger(**kwargs)
        log.info("Queuing <%s> <%s>" % (schedule_type, lookup_id))

        task_run = QueueTaskRun()
        task_run.task_id = self.request.id or uuid4()
        task_run.started_at = now()
        tr_qs = QueueTaskRun.objects

        # Load the schedule active items
        schedules = Schedule.objects.filter(enabled=True)
        if schedule_type == "crontab":
            schedules = schedules.filter(celery_cron_definition=lookup_id)
            tr_qs = tr_qs.filter(celery_cron_definition=lookup_id)
            scheduler_type = CrontabSchedule
            task_run.celery_cron_definition_id = lookup_id
        elif schedule_type == "interval":
            schedules = schedules.filter(celery_interval_definition=lookup_id)
            tr_qs = tr_qs.filter(celery_interval_definition=lookup_id)
            scheduler_type = IntervalSchedule
            task_run.celery_interval_definition_id = lookup_id

        # Confirm that this task should run now based on last run time.
        try:
            last_task_run = tr_qs.latest("started_at")
        except QueueTaskRun.DoesNotExist:
            # No previous run so it is safe to continue.
            pass
        else:
            # This basicly replicates what celery beat is meant to do, but
            # we can't trust celery beat and django-celery to always accurately
            # update their own last run time.
            sched = scheduler_type.objects.get(id=lookup_id)
            due, due_next = sched.schedule.is_due(last_task_run.started_at)
            if not due and due_next >= settings.DEFAULT_CLOCK_SKEW_SECONDS:
                return (
                    "Aborted Queuing <%s> <%s> due to last task run (%s) "
                    "at %s"
                    % (
                        schedule_type,
                        lookup_id,
                        last_task_run.id,
                        last_task_run.started_at,
                    )
                )

        task_run.save()
        # create tasks for each active schedule
        queued = 0
        schedules = schedules.values("id", "auth_token", "endpoint", "payload")
        for schedule in schedules.iterator():
            schedule["schedule_id"] = str(schedule.pop("id"))
            DeliverTask.apply_async(kwargs=schedule)
            queued += 1

        task_run.completed_at = now()
        task_run.save()
        return "Queued <%s> Tasks" % (queued,)
1317145
def change_execution_time(self, job, date_time):
        
        with self.connection.pipeline() as pipe:
            while 1:
                try:
                    pipe.watch(self.scheduled_jobs_key)
                    if pipe.zscore(self.scheduled_jobs_key, job.id) is None:
                        raise ValueError('Job not in scheduled jobs queue')
                    pipe.zadd(self.scheduled_jobs_key, {job.id: to_unix(date_time)})
                    break
                except WatchError:
                    # If job is still in the queue, retry otherwise job is already executed
                    # so we raise an error
                    if pipe.zscore(self.scheduled_jobs_key, job.id) is None:
                        raise ValueError('Job not in scheduled jobs queue')
                    continue
684649
def run time=nil

      puts "[cron] run called #{Time.now}" if @debug
      time = self.time if time.nil?
      self.each { |cron_job|
        ok,details = cron_job.runnable?(time)
        if ok then
          @queue.enq(cron_job)
          if cron_job.once? then
            cron_job[:delete] = true
          end
        end
      }
      self.reject! { |cron_job|
        cron_job[:delete]
      }
    end
1325207
def schedule_in(self, job, timedelta):
        
        now = long(self._now() * 1e6)
        when = now + timedelta.total_seconds() * 1e6
        self.schedule(job, when)
278115
public function isWaiting(Job $job) {
        $parent_waiting = false;
        if ($job->parent_id != null) {
            $parent_job = $this->getDependency($job);
            $parent_waiting = $this->isWaiting($parent_job);
        }

        $runner = $this->getJobRunner($job);

        return ($runner->isWaiting($job) || $parent_waiting);
    }
20429
def wait_for_jobs(jobs):
    

    all_running = False
    while not all_running:
        all_running = True
        time.sleep(5)
        for job in jobs:
            job.refresh()
            scheduled = getattr(job, "scheduled_at", None)
            if scheduled is not None:
                logger.info("Waiting for %s on %s [%s]" % (job.uid,
                                                           job.site,
                                                           _date2h(scheduled)))
            all_running = all_running and job.state == "running"
            if job.state == "error":
                raise Exception("The job %s is in error state" % job)
    logger.info("All jobs are Running !")
1081593
def IsRunning(self):
    """"""
    current_urn = self.Get(self.Schema.CURRENT_FLOW_URN)
    if not current_urn:
      return False

    try:
      current_flow = aff4.FACTORY.Open(
          urn=current_urn, aff4_type=flow.GRRFlow, token=self.token, mode="r")
    except aff4.InstantiationError:
      # This isn't a flow, something went really wrong, clear it out.
      logging.error("Unable to open cron job run: %s", current_urn)
      self.DeleteAttribute(self.Schema.CURRENT_FLOW_URN)
      self.Flush()
      return False

    return current_flow.GetRunner().IsRunning()
694528
def times(job):
  """"""
  timing = "Submitted: %s" % job.submit_time.ctime()
  if job.start_time is not None:
    timing += "\nStarted  : %s \t Job waited  : %s" % (job.start_time.ctime(), job.start_time - job.submit_time)
  if job.finish_time is not None:
    timing += "\nFinished : %s \t Job executed: %s" % (job.finish_time.ctime(), job.finish_time - job.start_time)
  return timing
582430
def ReadCronJobRun(self, job_id, run_id):
    """"""
    for run in itervalues(self.cronjob_runs):
      if run.cron_job_id == job_id and run.run_id == run_id:
        return run
    raise db.UnknownCronJobRunError(
        "Run with job id %s and run id %s not found." % (job_id, run_id))
635969
def _check_max_running(self, func, data, opts, now):
        '''
        
        '''
        # Check to see if there are other jobs with this
        # signature running.  If there are more than maxrunning
        # jobs present then don't start another.
        # If jid_include is False for this job we can ignore all this
        # NOTE--jid_include defaults to True, thus if it is missing from the data
        # dict we treat it like it was there and is True

        # Check if we're able to run
        if not data['run']:
            return data
        if 'jid_include' not in data or data['jid_include']:
            jobcount = 0
            if self.opts['__role'] == 'master':
                current_jobs = salt.utils.master.get_running_jobs(self.opts)
            else:
                current_jobs = salt.utils.minion.running(self.opts)
            for job in current_jobs:
                if 'schedule' in job:
                    log.debug(
                        'schedule.handle_func: Checking job against fun '
                        '%s: %s', func, job
                    )
                    if data['name'] == job['schedule'] \
                            and salt.utils.process.os_is_running(job['pid']):
                        jobcount += 1
                        log.debug(
                            'schedule.handle_func: Incrementing jobcount, '
                            'now %s, maxrunning is %s',
                            jobcount, data['maxrunning']
                        )
                        if jobcount >= data['maxrunning']:
                            log.debug(
                                'schedule.handle_func: The scheduled job '
                                '%s was not started, %s already running',
                                data['name'], data['maxrunning']
                            )
                            data['_skip_reason'] = 'maxrunning'
                            data['_skipped'] = True
                            data['_skipped_time'] = now
                            data['run'] = False
                            return data
        return data
580254
def job_not_running(self, jid, tgt, tgt_type, minions, is_finished):
        '''
        
        '''
        ping_pub_data = yield self.saltclients['local'](tgt,
                                                        'saltutil.find_job',
                                                        [jid],
                                                        tgt_type=tgt_type)
        ping_tag = tagify([ping_pub_data['jid'], 'ret'], 'job')

        minion_running = False
        while True:
            try:
                event = self.application.event_listener.get_event(self,
                                                                  tag=ping_tag,
                                                                  timeout=self.application.opts['gather_job_timeout'])
                event = yield event
            except TimeoutException:
                if not event.done():
                    event.set_result(None)

                if not minion_running or is_finished.done():
                    raise tornado.gen.Return(True)
                else:
                    ping_pub_data = yield self.saltclients['local'](tgt,
                                                                    'saltutil.find_job',
                                                                    [jid],
                                                                    tgt_type=tgt_type)
                    ping_tag = tagify([ping_pub_data['jid'], 'ret'], 'job')
                    minion_running = False
                    continue

            # Minions can return, we want to see if the job is running...
            if event['data'].get('return', {}) == {}:
                continue
            if event['data']['id'] not in minions:
                minions[event['data']['id']] = False
            minion_running = True