Returns a new job ordered by most recent first
why this?
run newest first, some jobs get left behind
run oldest first, all jobs get left behind

@return \DJJob|false A job if one was successfully locked. Otherwise false.
337553
public function getNewJob() {
        # we can grab a locked job if we own the lock
        $rs = $this->runQuery("
            SELECT id
            FROM   " . self::$jobsTable . "
            WHERE  queue = ?
            AND    (run_at IS NULL OR NOW() >= run_at)
            AND    (locked_at IS NULL OR locked_by = ?)
            AND    failed_at IS NULL
            AND    attempts < ?
            ORDER BY created_at DESC
            LIMIT  10
        ", array($this->queue, $this->name, $this->max_attempts));

        // randomly order the 10 to prevent lock contention among workers
        shuffle($rs);

        foreach ($rs as $r) {
            $job = new DJJob($this->name, $r["id"], array(
                "max_attempts" => $this->max_attempts,
                "fail_on_output" => $this->fail_on_output
            ));
            if ($job->acquireLock()) return $job;
        }

        return false;
    }
501490
private JobStory getNextJobFiltered() throws IOException {
    while (true) {
      ZombieJob job = producer.getNextJob();
      if (job == null) {
        return null;
      }
      if (job.getOutcome() == Pre21JobHistoryConstants.Values.KILLED) {
        continue;
      }
      if (job.getNumberMaps() == 0) {
        continue;
      }
      if (job.getNumLoggedMaps() == 0) {
        continue;
      }
      return job;
    }
  }
695908
@VisibleForTesting
    boolean runNextJob() {
        try {
            Queue<Message> messages = _messageSupplier.get();
            Message message;

            while ((message = messages.poll()) != null) {
                String jobIdString = (String) message.getPayload();

                // If this job has recently reported that it cannot run on this server then skip it.
                Instant now = Instant.now();
                Instant delayUntilTime = _recentNotOwnerDelays.get(jobIdString, EPOCH);
                if (now.isBefore(delayUntilTime)) {
                    _log.debug("Waiting {} for next attempt to run job locally: {}",
                            Duration.between(now, delayUntilTime), jobIdString);
                    continue;
                }

                InterProcessMutex mutex = getMutex(jobIdString);

                if (!acquireMutex(mutex)) {
                    _log.debug("Failed to get mutex for job {}", jobIdString);
                    continue;
                }
                try {
                    String jobTypeName = getJobTypeNameFromId(jobIdString);
                    RegistryEntry<?, ?> entry = _jobHandlerRegistry.getRegistryEntry(jobTypeName);

                    _log.info("Executing job {}... ", jobIdString);

                    boolean ranLocally = run(jobIdString, entry);

                    if (ranLocally) {
                        acknowledgeQueueMessage(message.getId());
                        _log.info("Executing job {}... DONE", jobIdString);
                    } else {
                        // The job self-reported it could not be run locally.  Cache that knowledge and wait before
                        // attempting this job again.
                        _recentNotOwnerDelays.put(jobIdString, Instant.now().plus(_notOwnerRetryDelay));
                        _recentNotOwnerDelays.cleanUp();
                        _log.info("Executing job {}... not local", jobIdString);
                    }
                } finally {
                    mutex.release();
                }

                return true;
            }

            _log.debug("Job queue was empty or contained only non-local jobs");
        } catch (Throwable t) {
            _log.warn("runNextJob failed unexpectedly", t);
        }

        return false;
    }
427833
protected function getNextAvailableJob($queue)
    {
        $job = $this->database->table($this->table)
            ->lockForUpdate()
            ->where('queue', $this->getQueue($queue))
            ->where(function ($query)
            {
                $this->isAvailable($query);

                $this->isReservedButExpired($query);
            })
            ->orderBy('id', 'asc')
            ->first();

        if (! is_null($job)) {
            return (object) $job;
        }
    }
1003531
public function hasPendingJob()
    {
        // We care about any queued job in the immediate queue, or any queue if the job is already running
        /** @var QueuedJobDescriptor $immediateJob */
        $immediateJob = $this->getQueuedJobService()
            ->getJobList(QueuedJob::IMMEDIATE)
            ->filter([
                'Implementation' => CheckForUpdatesJob::class
            ])
            ->exclude([
                'JobStatus' => [
                    QueuedJob::STATUS_COMPLETE,
                    QueuedJob::STATUS_CANCELLED,
                    QueuedJob::STATUS_BROKEN
                ]
            ]);

        /** @var QueuedJobDescriptor $runningJob */
        $runningJob = QueuedJobDescriptor::get()
            ->filter([
                'Implementation' => CheckForUpdatesJob::class,
                'JobStatus' => QueuedJob::STATUS_RUN,
            ]);

        return $immediateJob->exists() || $runningJob->exists();
    }
673153
public function getInstance()
	{
		if (!is_null($this->instance)) {
			return $this->instance;
		}

        $this->instance = $this->getJobFactory()->create($this->payload['class'], $this->getArguments(), $this->queue);
        $this->instance->job = $this;
        return $this->instance;
	}
789504
public function reorder()
    {
        $data = input('data');
        $pos  = input('pos');
        if (is_null($data) or is_null($pos)) {
            return false;
        }
        $unserialize    = unserialize(decrypt($data));
        $modelClass     = array_get($unserialize, 'model');
        $datatableClass = array_get($unserialize, 'datatable');

        if (!class_exists($modelClass) or ! class_exists($datatableClass)) {
            return false;
        }
        return app('events')->dispatch(new Reorder($modelClass, $datatableClass, $pos));
    }
1371396
public function index()
    {
        $jobs = Job::onTeam()
            ->where('start', '>', Carbon::now()->yesterday())
            ->with(
                'members',
                'member_tags',
                'location'
            )
            ->orderBy('start', 'asc')
            ->paginate(config('app.pagination_default'));
        return fractal($jobs, new JobTransformer())
            ->withResourceName('job')
            ->respond();
    }
560858
public function process()
    {
        $maxJobs = $this->scopeConfig->getValue('springbot/queue/max_jobs');
        if (!is_numeric($maxJobs)) {
            $maxJobs = 1;
        }

        for ($i = 1; $i <= $maxJobs; $i++) {
            if ($this->runNextJob() === null) {
                return null;
            }
        }
        return true;
    }
883224
public function requestJob()
    {
        $findCond = [
            'conditions' => [
                'completed' => 0
            ],
            'order' => [
                'created ASC',
                'id ASC',
            ],
            'limit' => 3,
        ];

        $jobs = $this->find('all', $findCond)->all()->toArray();
        for ($i=0; $i<count($jobs); $i++) {
            if ($jobs[$i]['stats']['tries'] >= $this->maxTries) {
                unset($jobs[$i]);
            }
        }
        return $jobs;
    }
1107959
protected function _initJob()
    {
        $jobCode = $this->getRequest()->getParam('job_code', null);
        $job = Mage::getModel('aoe_scheduler/job')->load($jobCode);
        Mage::register('current_job_instance', $job);
        return $job;
    }
42325
public function last()
    {
        $this->seek($this->count() - 1);

        if ($this->count()) {
            return $this->rows[ $this->position ];
        }

        return new Row();
    }
570616
public function reserve()
    {
        $queues = $this->queues();
        if(!is_array($queues)) {
            return;
        }

        foreach($queues as $queue) {
            $this->log('Checking ' . $queue, self::LOG_VERBOSE);
            $job = Job::reserve($queue);
            if($job) {
                $this->log('Found job on ' . $queue, self::LOG_VERBOSE);
                return $job;
            }
        }

        return false;
    }
205817
public function getPrev()
    {
        return self::find()->where(['<', 'id', $this->id])->orderBy(['id' => SORT_DESC])->limit(1)->one();
    }
203713
private function getJobRunner(Job $job) {
        if (!$this->runner_pool->has($job->runner_class)) {
            $runner = new $job->runner_class();
            $this->runner_pool->add($runner);
        }
        $runner = $this->runner_pool->get($job->runner_class);

        return $runner;
    }
704101
public function getDateLastCronRun($cronJob)
    {
        $collection = $this->schelduleFactory->create()
            ->getCollection()
            ->addFieldToFilter('status', \Magento\Cron\Model\Schedule::STATUS_SUCCESS)
            ->addFieldToFilter('job_code', $cronJob);
        //limit and order the results
        $collection->getSelect()
            ->limit(1)
            ->order('executed_at DESC');

        if ($collection->getSize() == 0) {
            return false;
        }
        $executedAt = $collection->getFirstItem()->getExecutedAt();

        return $executedAt;
    }
62499
protected function getJobsEarliestTryAt()
    {
        $tryAt = date('Y-m-d H:i:s');

        foreach ($this->jobs as $job) {
            if (!$job->isFinished() && Helper::datetimeLT($job->getTryAt(), $tryAt)) {
                $tryAt = $job->getTryAt();
            }
        }

        return $tryAt;
    }