Returns a list of job instances that should be queued
        (score lower than current timestamp).
        If with_times is True a list of tuples consisting of the job instance and
        it's scheduled execution time is returned.
16183
def get_jobs_to_queue(self, with_times=False):
        
        return self.get_jobs(to_unix(datetime.utcnow()), with_times=with_times)
199015
def getnjobs(self, key, **kwargs):
        

        return self.get(key, cast_func=parse_n_jobs, **kwargs)
693714
def queue_task
      if @task.job_class.instance_method(:perform).arity.zero?
        @task.job_class.send(perform_method)
      else
        @task.job_class.send(perform_method, @scheduled_time.to_i)
      end
    end
185876
def enqueue_jobs(self, jobs: Iterable[Job]):
        """"""
        for job in jobs:
            if job.should_start:
                job.status = JobStatus.QUEUED
                queue = self._get_queue(job.queue)
                queue.put(job.serialize())
            else:
                with self._lock:
                    job.status = JobStatus.WAITING
                    self._future_jobs.append(job.serialize())
                    self._future_jobs.sort(key=lambda j: Job.deserialize(j).at)
        self._something_happened.set()
798598
def list_current_jobs(self):
        
        jobs = {}
        for job in self.scheduler.get_jobs():
            if job.name not in ('schedule_jobs', 'process_status_queue'):
                jobs[job.name] = job

        return jobs
1356478
def getRunningBatchJobIDs(self):
        
        # Example lines..
        # r 5410186 benedictpaten worker 1247029663 localhost
        # r 5410324 benedictpaten worker 1247030076 localhost
        runningJobs = {}
        issuedJobs = self.getIssuedBatchJobIDs()
        for line in self._runParasol(['pstat2'])[1]:
            if line != '':
                match = self.runningPattern.match(line)
                if match is not None:
                    jobID = int(match.group(1))
                    startTime = int(match.group(2))
                    if jobID in issuedJobs:  # It's one of our jobs
                        runningJobs[jobID] = time.time() - startTime
        return runningJobs
521296
def get_recent_jobs(self, n_jobs=10):
        

        # Query the server for the list of jobs
        request = urllib.request.Request(self.url + '/rest/v1/jobs/?pageSize=' +
                                         str(n_jobs) + '&userId=' + str(urllib.parse.quote(self.username)) +
                                         '&orderBy=-dateSubmitted')
        if self.authorization_header() is not None:
            request.add_header('Authorization', self.authorization_header())
        request.add_header('User-Agent', 'GenePatternRest')
        response = urllib.request.urlopen(request)
        response_string = response.read().decode('utf-8')
        response_json = json.loads(response_string)

        # For each job in the JSON Array, build a GPJob object and add to the job list
        job_list = []
        for job_json in response_json['items']:
            job_id = job_json['jobId']
            job = GPJob(self, job_id)
            job.info = job_json
            job.load_info()
            job_list.append(job)

        return job_list
1116912
private boolean isScheduled(JobInProgress job) {
    return ((job.pendingMaps() < job.desiredMaps()) 
        || (job.pendingReduces() < job.desiredReduces()));
  }
31714
def jobs(opts={})

      opts = { opts => true } if opts.is_a?(Symbol)

      jobs = @jobs.to_a

      if opts[:running]
        jobs = jobs.select { |j| j.running? }
      elsif ! opts[:all]
        jobs = jobs.reject { |j| j.next_time.nil? || j.unscheduled_at }
      end

      tags = Array(opts[:tag] || opts[:tags]).collect(&:to_s)
      jobs = jobs.reject { |j| tags.find { |t| ! j.tags.include?(t) } }

      jobs
    end
3637
def get_queues(*queue_names, **kwargs):
    
    from .settings import QUEUES

    if len(queue_names) <= 1:
        # Return "default" queue if no queue name is specified
        # or one queue with specified name
        return [get_queue(*queue_names, **kwargs)]

    # will return more than one queue
    # import job class only once for all queues
    kwargs['job_class'] = get_job_class(kwargs.pop('job_class', None))

    queue_params = QUEUES[queue_names[0]]
    connection_params = filter_connection_params(queue_params)
    queues = [get_queue(queue_names[0], **kwargs)]

    # do consistency checks while building return list
    for name in queue_names[1:]:
        queue = get_queue(name, **kwargs)
        if type(queue) is not type(queues[0]):
            raise ValueError(
                'Queues must have the same class.'
                '"{0}" and "{1}" have '
                'different classes'.format(name, queue_names[0]))
        if connection_params != filter_connection_params(QUEUES[name]):
            raise ValueError(
                'Queues must have the same redis connection.'
                '"{0}" and "{1}" have '
                'different connections'.format(name, queue_names[0]))
        queues.append(queue)

    return queues
616584
def all(cls):
        

        # Start with raw queues we know exist from the config
        queues = {x: 0 for x in Queue.get_queues_config()}

        stats = list(context.connections.mongodb_jobs.mrq_jobs.aggregate([
            {"$match": {"status": "queued"}},
            {"$group": {"_id": "$queue", "jobs": {"$sum": 1}}}
        ]))

        queues.update({x["_id"]: x["jobs"] for x in stats})

        return queues
593440
def existing_jobs
      @existing_jobs ||= SimpleScheduler::Task.scheduled_set.select do |job|
        next unless job.display_class == "SimpleScheduler::FutureJob"

        task_params = job.display_args[0].symbolize_keys
        task_params[:class] == job_class_name && task_params[:name] == name
      end.to_a
    end
1252624
def list(self, request, project):
        
        MAX_JOBS_COUNT = 2000

        # make a mutable copy of these params
        filter_params = request.query_params.copy()

        # various hacks to ensure API backwards compatibility
        for param_key in filter_params.keys():
            # replace `result_set_id` with `push_id`
            if param_key.startswith('result_set_id'):
                new_param_key = param_key.replace('result_set_id', 'push_id')
                filter_params[new_param_key] = filter_params[param_key]
                del filter_params[param_key]
            # convert legacy timestamp parameters to time ones
            elif param_key in ['submit_timestamp', 'start_timestamp',
                               'end_timestamp']:
                new_param_key = param_key.replace('timestamp', 'time')
                filter_params[new_param_key] = datetime.datetime.fromtimestamp(
                    float(filter_params[param_key]))
                del filter_params[param_key]
            # sanity check 'last modified'
            elif param_key.startswith('last_modified'):
                datestr = filter_params[param_key]
                try:
                    parser.parse(datestr)
                except ValueError:
                    return Response(
                        "Invalid date value for `last_modified`: {}".format(datestr),
                        status=HTTP_400_BAD_REQUEST)

        try:
            offset = int(filter_params.get("offset", 0))
            count = int(filter_params.get("count", 10))
        except ValueError:
            return Response(
                "Invalid value for offset or count",
                status=HTTP_400_BAD_REQUEST)
        return_type = filter_params.get("return_type", "dict").lower()

        if count > MAX_JOBS_COUNT:
            msg = "Specified count exceeds API MAX_JOBS_COUNT value: {}".format(MAX_JOBS_COUNT)
            return Response({"detail": msg}, status=HTTP_400_BAD_REQUEST)

        try:
            repository = Repository.objects.get(name=project)
        except Repository.DoesNotExist:
            return Response({
                "detail": "No project with name {}".format(project)
            }, status=HTTP_404_NOT_FOUND)
        jobs = JobFilter({k: v for (k, v) in filter_params.items()},
                         queryset=Job.objects.filter(
                             repository=repository).select_related(
                                 *self._default_select_related)).qs

        response_body = self._get_job_list_response(jobs, offset, count,
                                                    return_type)
        response_body["meta"] = dict(repository=project, offset=offset,
                                     count=count)

        return Response(response_body)
53571
def get_expired_tasks(self, key_prefix, time, batch_size, client=None):
        
        result = self._get_expired_tasks(args=[key_prefix, time, batch_size],
                                         client=client)

        # [queue1, task1, queue2, task2] -> [(queue1, task1), (queue2, task2)]
        return list(zip(result[::2], result[1::2]))
1329746
def returnJobReqs(self, jobReqs):
        
        # Since we are only reading this job's specific values from the state file, we don't
        # need a lock
        jobState = self._JobState(self._CacheState._load(self.cacheStateFile
                                                         ).jobState[self.jobID])
        for x in list(jobState.jobSpecificFiles.keys()):
            self.deleteLocalFile(x)
        with self._CacheState.open(self) as cacheInfo:
            cacheInfo.sigmaJob -= jobReqs
1024461
def pending_tasks(self, res):
        ""
        jobs, lock = self._jobs
        with lock:
            return jobs[res].copy()
1069583
private boolean jobHasScheduledStatus() {

		final Iterator<ExecutionVertex> it = new ExecutionGraphIterator(this, true);

		while (it.hasNext()) {

			final ExecutionState s = it.next().getExecutionState();
			if (s != ExecutionState.CREATED && s != ExecutionState.SCHEDULED && s != ExecutionState.READY) {
				return false;
			}
		}

		return true;
	}