Abort this job, potentially rescheduling a replacement if there is still work to do
480129
protected function discardJob()
    {
        $this->skipped = true;

        // If we do not have dirty records, then assume that these dirty records were committed
        // already this request (but probably another job), so we don't need to commit anything else.
        // This could occur if we completed multiple searchupdate jobs in a prior request, and
        // we only need one commit job to commit all of them in the current request.
        if (empty(static::$dirty_indexes)) {
            $this->addMessage("Indexing already completed this request: Discarding this job");
            return;
        }


        // If any commit has run, but some (or all) indexes are un-comitted, we must re-schedule this task.
        // This could occur if we completed a searchupdate job in a prior request, as well as in
        // the current request
        $cooldown = Config::inst()->get(__CLASS__, 'cooldown');
        $now = new DateTime(DBDatetime::now()->getValue());
        $now->add(new DateInterval('PT' . $cooldown . 'S'));
        $runat = $now->Format('Y-m-d H:i:s');

        $this->addMessage("Indexing already run this request, but incomplete. Re-scheduling for {$runat}");

        // Queue after the given cooldown
        static::queue(false, $runat);
    }
111627
def run_later(self, callable_, timeout, *args, **kwargs):
        

        self.lock.acquire()
        try:
            if self.die:
                raise RuntimeError('This timer has been shut down and '
                                   'does not accept new jobs.')

            job = TimerTask(callable_, *args, **kwargs)
            self._jobs.append((job, time.time() + timeout))
            self._jobs.sort(key=lambda j: j[1])  # sort on time
            self.lock.notify()

            return job
        finally:
            self.lock.release()
159575
def cancel(self):
    

    with synchronized(self):
      cancelled = self.__cancelled
      if not cancelled:
        self.__cancelled = True
        notify_all(self)

    if not cancelled:
      self._trigger_event(Job.CANCELLED)
732718
def modify_job(self, name, schedule, persist=True):
        '''
        
        '''
        # ensure job exists, then replace it
        if name in self.opts['schedule']:
            self.delete_job(name, persist)
        elif name in self._get_schedule(include_opts=False):
            log.warning("Cannot modify job %s, it's in the pillar!", name)
            return

        self.opts['schedule'][name] = schedule

        if persist:
            self.persist()
1353825
def external_aborted(self, params):
        
        self.ended = True
        self.running = False

        # When the server sends an abort signal, we really have to close immediately,
        # since for example the job has been already deleted.
        # without touching the git and client any further
        os._exit(1)
1337627
def abort(job_id):
    
    job = logs.dbcmd('get_job', job_id)  # job_id can be negative
    if job is None:
        print('There is no job %d' % job_id)
        return
    elif job.status not in ('executing', 'running'):
        print('Job %d is %s' % (job.id, job.status))
        return
    name = 'oq-job-%d' % job.id
    for p in psutil.process_iter():
        if p.name() == name:
            try:
                os.kill(p.pid, signal.SIGTERM)
                logs.dbcmd('set_status', job.id, 'aborted')
                print('Job %d aborted' % job.id)
            except Exception as exc:
                print(exc)
            break
    else:  # no break
        # set job as failed if it is set as 'executing' or 'running' in the db
        # but the corresponding process is not running anymore
        logs.dbcmd('set_status', job.id, 'failed')
        print('Unable to find a process for job %d,'
              ' setting it as failed' % job.id)
1116912
private boolean isScheduled(JobInProgress job) {
    return ((job.pendingMaps() < job.desiredMaps()) 
        || (job.pendingReduces() < job.desiredReduces()));
  }
1351734
function requestWork(root, expirationTime) {
    if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
      invariant(false, 'Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.');
    }

    // Add the root to the schedule.
    // Check if this root is already part of the schedule.
    if (root.nextScheduledRoot === null) {
      // This root is not already scheduled. Add it.
      root.remainingExpirationTime = expirationTime;
      if (lastScheduledRoot === null) {
        firstScheduledRoot = lastScheduledRoot = root;
        root.nextScheduledRoot = root;
      } else {
        lastScheduledRoot.nextScheduledRoot = root;
        lastScheduledRoot = root;
        lastScheduledRoot.nextScheduledRoot = firstScheduledRoot;
      }
    } else {
      // This root is already scheduled, but its priority may have increased.
      var remainingExpirationTime = root.remainingExpirationTime;
      if (remainingExpirationTime === NoWork || expirationTime < remainingExpirationTime) {
        // Update the priority.
        root.remainingExpirationTime = expirationTime;
      }
    }

    if (isRendering) {
      // Prevent reentrancy. Remaining work will be scheduled at the end of
      // the currently rendering batch.
      return;
    }

    if (isBatchingUpdates) {
      // Flush work at the end of the batch.
      if (isUnbatchingUpdates) {
        // ...unless we're inside unbatchedUpdates, in which case we should
        // flush it now.
        nextFlushedRoot = root;
        nextFlushedExpirationTime = Sync;
        performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime);
      }
      return;
    }

    // TODO: Get rid of Sync and use current time?
    if (expirationTime === Sync) {
      performWork(Sync, null);
    } else {
      scheduleCallbackWithExpiration(expirationTime);
    }
  }
1079134
function() {
        for( var i = 0; i < this.jobQueue.length; i++ ) {
            var job = this.jobQueue[i];
            if ( typeof job.abort === "function" ) {
                job.abort();
            }
        }

        this.jobQueue = [];
    }
164628
def delete_job_prefix(self, name, persist=True):
        '''
        
        '''
        # ensure job exists, then delete it
        for job in list(self.opts['schedule'].keys()):
            if job.startswith(name):
                del self.opts['schedule'][job]
        for job in self._get_schedule(include_opts=False):
            if job.startswith(name):
                log.warning("Cannot delete job %s, it's in the pillar!", job)

        # Fire the complete event back along with updated list of schedule
        evt = salt.utils.event.get_event('minion', opts=self.opts, listen=False)
        evt.fire_event({'complete': True,
                        'schedule': self._get_schedule()},
                       tag='/salt/minion/minion_schedule_delete_complete')

        # remove from self.intervals
        for job in list(self.intervals.keys()):
            if job.startswith(name):
                del self.intervals[job]

        if persist:
            self.persist()
283918
private void removeScheduledJob(UUID jobId, boolean complete) {
    ScheduledJob sched = jobs.remove(jobId);
    if (sched != null) {
      if (complete) {
        sched.notifyComplete();
        if (logger.isInfoEnabled()) {
          logger.info("Job complete (" + jobId.toString() + ")");
        }
      } else {
        sched.notifyCancelled();
        if (logger.isInfoEnabled()) {
          logger.info("Job cancelled (" + jobId.toString() + ")");
        }
      }
      jobs.remove(jobId);
      scheduler.removeJob(jobId);
      sched.classManager.release();
    }
  }
511640
def delay_job(self, job, delayed_until):
        
        timestamp = datetime_to_score(delayed_until)
        self.delayed.zadd(timestamp, job.ident)
1202272
boolean maybeSchedule()
    {
        if (pool.spinningCount.get() > 0 || !takeWorkPermit(true))
            return false;

        pool.schedule(new Work(this));
        return true;
    }
77070
def abort(self):
        """"""
        for sbi_id in self.sbi_ids:
            sbi = SchedulingBlockInstance(sbi_id)
            sbi.abort()
        self.set_state('ABORTED')
1149633
def requeue_delayed_jobs(self):
        
        lock_key = self.make_key(
            self._name,
            self.pk.get(),
            "requeue_all_delayed_ready_jobs",
        )
        connection = self.get_connection()

        if connection.exists(lock_key):
            # if locked, a worker is already on it, don't wait and exit
            return []

        with Lock(connection, lock_key, timeout=60):

            # stop here if we know we have nothing
            first_delayed_time = self.first_delayed_time
            if not first_delayed_time:
                return []

            # get when we are :)
            now_timestamp = datetime_to_score(datetime.utcnow())

            # the first job will be ready later, and so the other ones too, then
            # abort
            if float(first_delayed_time) > now_timestamp:
                return []

            failures = []
            while True:
                # get the first entry
                first_entry = self.first_delayed

                # no first entry, another worker took all from us !
                if not first_entry:
                    break

                # split into vars for readability
                job_ident, delayed_until = first_entry

                # if the date of the job is in the future, another work took the
                # job we wanted, so we let this job here and stop the loop as we
                # know (its a zset sorted by date) that no other jobs are ready
                if delayed_until > now_timestamp:
                    break

                # remove the entry we just got from the delayed ones
                self.delayed.zrem(job_ident)

                # and add it to the waiting queue
                try:
                    job = Job.get_from_ident(job_ident)
                    if job.status.hget() == STATUSES.DELAYED:
                        job.status.hset(STATUSES.WAITING)
                    self.enqueue_job(job)
                except Exception as e:
                    failures.append((job_ident, '%s' % e))

            return failures
934823
private void reorderJobs(JobInProgress job, JobSchedulingInfo oldInfo, 
                           QueueInfo qi) {
    
    if(qi.removeWaitingJob(oldInfo) != null) {
      qi.addWaitingJob(job);
    }
    if(qi.removeRunningJob(oldInfo) != null) {
      qi.addRunningJob(job);
    }
  }
19052
def stalled(self, offset=0, count=25):
        ''''''
        return self.client('jobs', 'stalled', self.name, offset, count)