Sort jobs by priority and then by start time.
340039
private synchronized void resortInitQueue() {
    Comparator<JobInProgress> comp = new Comparator<JobInProgress>() {
      public int compare(JobInProgress o1, JobInProgress o2) {
        int res = o1.getPriority().compareTo(o2.getPriority());
        if(res == 0) {
          if(o1.getStartTime() < o2.getStartTime())
            res = -1;
          else
            res = (o1.getStartTime()==o2.getStartTime() ? 0 : 1);
        }
          
        return res;
      }
    };
    
    synchronized (jobInitQueue) {
      Collections.sort(jobInitQueue, comp);
    }
  }
734109
def schedule(self, task):
        """"""
        self.task_manager.register(task)
        self.worker_manager.dispatch(task)
671687
private void selectionSort(final T[] array, int start, int end, Comparator<T> lt) {
    int i;
    int j;
    int bestI;
    T tmp;
    for (i = start; i < end; i++) {
      bestI = i;
      for (j = i + 1; j < end; j++) {
        if (lt.compare(array[j], array[bestI]) < 0)
          bestI = j;
      }
      tmp = array[i];
      array[i] = array[bestI];
      array[bestI] = tmp;
    }
  }
278038
def __sort_up(self):
        """"""
        if self.__do_need_sort_up:
            self.__up_objects.sort(self.__up_cmp)
            self.__do_need_sort_up = False
367068
def clean_old_jobs():
    '''
    
    '''
    if __opts__.get('keep_jobs', False) and int(__opts__.get('keep_jobs', 0)) > 0:
        try:
            with _get_serv() as cur:
                sql = "select (NOW() -  interval '{0}' hour) as stamp;".format(__opts__['keep_jobs'])
                cur.execute(sql)
                rows = cur.fetchall()
                stamp = rows[0][0]

            if __opts__.get('archive_jobs', False):
                _archive_jobs(stamp)
            else:
                _purge_jobs(stamp)
        except Exception as e:
            log.error(e)
452246
public void logJobPriority(JobID jobid, JobPriority priority) {
    if (disableHistory) {
      return;
    }

    if (null != writers) {
      log(writers, RecordTypes.Job,
          new Keys[] {Keys.JOBID, Keys.JOB_PRIORITY},
          new String[] {jobId.toString(), priority.toString()});
    }
  }
742203
public void startPriority(Runnable task)
  {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();

    // long expire = CurrentTime.getCurrentTimeActual() + PRIORITY_TIMEOUT;
    long expire = MAX_EXPIRE;

    boolean isPriority = true;
    boolean isQueue = true;
    boolean isWake = true;

    if (! scheduleImpl(task, loader, expire, isPriority, isQueue, isWake)) {
      String msg = (this + " unable to start priority thread " + task
                    + " pri-min=" + getPriorityIdleMin()
                    + " thread=" + getThreadCount()
                    + " idle=" + getThreadIdleCount()
                    // + " pri-idle=" + getPriorityIdleCount()
                    + " starting=" + getThreadStartingCount()
                    + " max=" + getThreadMax());

      log.warning(msg);

      HealthSystemFacade.fireEvent(THREAD_FULL_EVENT, msg);

      OverflowThread item = new OverflowThread(task);
      item.start();
    }
  }
946229
def _main_loop(self):
        
        fetch_priorities_delay = timedelta(seconds=self.fetch_priorities_delay)
        fetch_delayed_delay = timedelta(seconds=self.fetch_delayed_delay)

        while not self.must_stop():
            self.set_status('waiting')

            if self.last_update_keys + fetch_priorities_delay < datetime.utcnow():
                self.update_keys()

            if self.last_requeue_delayed + fetch_delayed_delay < datetime.utcnow():
                self.requeue_delayed_jobs()

            try:
                queue_and_job = self.wait_for_job()
                if queue_and_job is None:
                    # timeout for blpop
                    continue
                queue, job = queue_and_job
            except Exception as e:
                self.log('Unable to get job: %s\n%s'
                    % (str(e), traceback.format_exc()), level='error')
            else:
                self.num_loops += 1
                try:
                    identifier = 'pk:%s' % job.pk.get()
                except Exception as e:
                    identifier = '??'
                try:
                    self.set_status('running')
                    identifier, status = job.hmget('identifier', 'status')
                     # some cache, don't count on it on subclasses
                    job._cached_identifier = identifier
                    job._cached_status = status
                    queue._cached_name = queue.name.hget()

                    if status == STATUSES.DELAYED:
                        self.job_delayed(job, queue)
                    elif status != STATUSES.WAITING:
                        self.job_skipped(job, queue)
                    else:
                        try:
                            self.job_started(job, queue)
                            job_result = self.callback(job, queue)
                        except Exception as e:
                            trace = None
                            if self.save_tracebacks:
                                trace = traceback.format_exc()
                            self.job_error(job, queue, e, trace)
                        else:
                            job._cached_status = job.status.hget()
                            if job._cached_status == STATUSES.DELAYED:
                                self.job_delayed(job, queue)
                            elif job._cached_status == STATUSES.CANCELED:
                                self.job_skipped(job, queue)
                            else:
                                self.job_success(job, queue, job_result)
                except Exception as e:
                    self.log('[%s] unexpected error: %s\n%s'
                        % (identifier, str(e), traceback.format_exc()), level='error')
                    try:
                        queue.errors.rpush(job.ident)
                    except Exception as e:
                        self.log('[%s] unable to add the error in the queue: %s\n%s'
                            % (identifier, str(e), traceback.format_exc()), level='error')
105818
def get_jobs():
    """"""

    jobs = current_app.apscheduler.get_jobs()

    job_states = []

    for job in jobs:
        job_states.append(job)

    return jsonify(job_states)
347867
def sort(records: Sequence[Record]) -> List[Record]:
    ""
    return sorted(records, key=_record_key)
584650
def list_jobs(tail):
    """"""
    query = (
        db.session.query(models.CrawlerJob)
        .order_by(models.CrawlerJob.id.desc())
    )
    if tail != 0:
        query = query.limit(tail)

    results = query.yield_per(10).all()
    _show_table(results=results)
61261
public void sort() {
        if (initial)
            Arrays.sort(data, 0, size, comparator);
        else if (size > limit)
            sortTail();
    }
1057380
def enqueue_jobs(self, jobs: Iterable[Job]):
        """"""
        jobs_to_queue = list()
        for job in jobs:
            if job.should_start:
                job.status = JobStatus.QUEUED
            else:
                job.status = JobStatus.WAITING
            jobs_to_queue.append(job.serialize())

        if jobs_to_queue:
            self._run_script(
                self._enqueue_job,
                self._to_namespaced(NOTIFICATIONS_KEY),
                self._to_namespaced(RUNNING_JOBS_KEY.format(self._id)),
                self.namespace,
                self._to_namespaced(FUTURE_JOBS_KEY),
                *jobs_to_queue
            )
907448
function sortByStart(a: AstLocation, b: AstLocation) {
  if (a.start.line < b.start.line) {
    return -1;
  } else if (a.start.line === b.start.line) {
    return a.start.column - b.start.column;
  }

  return 1;
}
786519
def priority(s):
    """"""
    # REZ: Previously this value was calculated in place many times which is
    #      expensive.  Do it once early.
    # REZ: Changed this to output a list, so that can nicely sort "validate"
    #      items by the sub-priority of their schema
    type_of_s = type(s)
    if type_of_s in (list, tuple, set, frozenset):
        return [ITERABLE]
    if type_of_s is dict:
        return [DICT]
    if issubclass(type_of_s, type):
        return [TYPE]
    if hasattr(s, 'validate'):
        p = [VALIDATOR]
        if hasattr(s, "_schema"):
            p.extend(priority(s._schema))
        return p
    if callable(s):
        return [CALLABLE]
    else:
        return [COMPARABLE]
831445
public function execute()
    {
        // sort jobs by priority
        $jobs = [];
        ksort($this->jobs);
        foreach ($this->jobs as $priority_jobs) {
            $jobs = array_merge($jobs, $priority_jobs);
        }

        /* @var $job Job */
        foreach ($jobs as $job) {
            $job->execute();
        }
    }
1195914
def convert_job(row: list) -> dict:
    """"""
    state = row[-2]
    start_time_raw = row[-4]
    end_time_raw = row[-3]
    if state not in ('PENDING', 'CANCELLED'):
        start_time = datetime.strptime(start_time_raw, '%Y-%m-%dT%H:%M:%S')
        if state != 'RUNNING':
            end_time = datetime.strptime(end_time_raw, '%Y-%m-%dT%H:%M:%S')
        else:
            end_time = None
    else:
        start_time = end_time = None

    # parse name of job
    job_name = row[1]
    step_name, step_context = job_name.rstrip('_BOTH').rstrip('_SV').rsplit('_', 1)

    return {
        'id': int(row[0]),
        'name': job_name,
        'step': step_name,
        'context': step_context,
        'state': state,
        'start': start_time,
        'end': end_time,
        'elapsed': time_to_sec(row[-5]),
        'cpu': time_to_sec(row[-6]),
        'is_completed': state == 'COMPLETED',
    }