// dequeueForSched is used to dequeue the next work item for a given scheduler.
// This assumes locks are held and that this scheduler has work
171876
func (b *EvalBroker) dequeueForSched(sched string) (*structs.Evaluation, string, error) {
	// Get the pending queue
	pending := b.ready[sched]
	raw := heap.Pop(&pending)
	b.ready[sched] = pending
	eval := raw.(*structs.Evaluation)

	// Generate a UUID for the token
	token := uuid.Generate()

	// Setup Nack timer
	nackTimer := time.AfterFunc(b.nackTimeout, func() {
		b.Nack(eval.ID, token)
	})

	// Add to the unack queue
	b.unack[eval.ID] = &unackEval{
		Eval:      eval,
		Token:     token,
		NackTimer: nackTimer,
	}

	// Increment the dequeue count
	b.evals[eval.ID] += 1

	// Update the stats
	b.stats.TotalReady -= 1
	b.stats.TotalUnacked += 1
	bySched := b.stats.ByScheduler[sched]
	bySched.Ready -= 1
	bySched.Unacked += 1

	return eval, token, nil
}
1007936
func (s *Scheduler) waitFor(ctx context.Context, op stackOperation, ss twelvefactor.StatusStream) func(*cloudformation.DescribeStacksInput) error {
	waiter := waiters[op]
	wait := waiter.wait(s.cloudformation)

	return func(input *cloudformation.DescribeStacksInput) error {
		tags := []string{
			fmt.Sprintf("stack:%s", *input.StackName),
		}
		publish(ctx, ss, waiter.startMessage)
		start := time.Now()
		err := wait(input)
		stats.Timing(ctx, fmt.Sprintf("scheduler.cloudformation.%s", op), time.Since(start), 1.0, tags)
		if err == nil {
			publish(ctx, ss, waiter.successMessage)
		}
		return err
	}
}
756719
func (c *Controller) enqueueWF(obj interface{}) {
	un, ok := obj.(*unstructured.Unstructured)
	if !ok {
		log.Warnf("'%v' is not an unstructured", obj)
		return
	}
	wf, err := util.FromUnstructured(un)
	if err != nil {
		log.Warnf("Failed to unmarshal workflow %v object: %v", obj, err)
		return
	}
	now := c.clock.Now()
	remaining, expiration := timeLeft(wf, &now)
	if remaining == nil || *remaining > c.resyncPeriod {
		return
	}
	log.Infof("Found Workflow %s/%s set expire at %v (%s from now)", wf.Namespace, wf.Name, expiration, remaining)
	var addAfter time.Duration
	if *remaining > 0 {
		addAfter = *remaining
	}
	var key string
	if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil {
		runtimeutil.HandleError(err)
		return
	}
	//c.workqueue.Add(key)
	log.Infof("Queueing workflow %s/%s for delete in %v", wf.Namespace, wf.Name, addAfter)
	c.workqueue.AddAfter(key, addAfter)
}
1340127
func (m *MockInterface) Scheduling() v1beta110.SchedulingV1beta1Interface {
	ret := m.ctrl.Call(m, "Scheduling")
	ret0, _ := ret[0].(v1beta110.SchedulingV1beta1Interface)
	return ret0
}
490537
func (l *Logger) Enqueue(ts ...Task) {
	if l == nil {
		for _, t := range ts {
			if t == nil {
				// NOTE: Do not allow nil tasks which are unable
				// to be completed.
				continue
			}
			go func(t Task) {
				for range t.Updates() {
					// Discard all updates.
				}
			}(t)
		}
		return
	}

	l.wg.Add(len(ts))
	for _, t := range ts {
		if t == nil {
			// NOTE: See above.
			continue
		}
		l.queue <- t
	}
}
1306450
func (woc *wfOperationCtx) requeue() {
	key, err := cache.MetaNamespaceKeyFunc(woc.wf)
	if err != nil {
		woc.log.Errorf("Failed to requeue workflow %s: %v", woc.wf.ObjectMeta.Name, err)
		return
	}
	woc.controller.wfQueue.Add(key)
}
707572
func (e *Enqueuer) EnqueueUniqueInByKey(jobName string, secondsFromNow int64, args map[string]interface{}, keyMap map[string]interface{}) (*ScheduledJob, error) {
	enqueue, job, err := e.uniqueJobHelper(jobName, args, keyMap)
	if err != nil {
		return nil, err
	}

	scheduledJob := &ScheduledJob{
		RunAt: nowEpochSeconds() + secondsFromNow,
		Job:   job,
	}

	res, err := enqueue(&scheduledJob.RunAt)
	if res == "ok" && err == nil {
		return scheduledJob, nil
	}
	return nil, err
}
800867
func (s *ScheduleExecution) RollForward(c context.Context) (muts []tumble.Mutation, err error) {
	a := model.AttemptFromID(s.For)
	if err = ds.Get(c, a); err != nil {
		logging.WithError(err).Errorf(c, "loading attempt")
		return
	}

	if a.State != dm.Attempt_SCHEDULING {
		logging.Infof(c, "EARLY EXIT: already scheduling")
		return
	}

	q := model.QuestFromID(s.For.Quest)
	if err = ds.Get(ds.WithoutTransaction(c), q); err != nil {
		logging.WithError(err).Errorf(c, "loading quest")
		return
	}

	prevResult := (*dm.JsonResult)(nil)
	if a.LastSuccessfulExecution != 0 {
		prevExecution := model.ExecutionFromID(c, s.For.Execution(a.LastSuccessfulExecution))
		if err = ds.Get(c, prevExecution); err != nil {
			logging.Errorf(c, "loading previous execution: %s", err)
			return
		}
		prevResult = prevExecution.Result.Data
	}

	reg := distributor.GetRegistry(c)
	dist, ver, err := reg.MakeDistributor(c, q.Desc.DistributorConfigName)
	if err != nil {
		logging.WithError(err).Errorf(c, "making distributor %s", q.Desc.DistributorConfigName)
		return
	}

	a.CurExecution++
	if err = a.ModifyState(c, dm.Attempt_EXECUTING); err != nil {
		logging.WithError(err).Errorf(c, "modifying state")
		return
	}

	eid := dm.NewExecutionID(s.For.Quest, s.For.Id, a.CurExecution)
	e := model.MakeExecution(c, eid, q.Desc.DistributorConfigName, ver)
	e.TimeToStart = google.DurationFromProto(q.Desc.Meta.Timeouts.Start)
	e.TimeToRun = google.DurationFromProto(q.Desc.Meta.Timeouts.Run)

	exAuth := &dm.Execution_Auth{Id: eid, Token: e.Token}

	var distTok distributor.Token
	distTok, e.TimeToStop, err = dist.Run(&q.Desc, exAuth, prevResult)
	if e.TimeToStop <= 0 {
		e.TimeToStop = google.DurationFromProto(q.Desc.Meta.Timeouts.Stop)
	}
	e.DistributorToken = string(distTok)
	if err != nil {
		if transient.Tag.In(err) {
			// tumble will retry us later
			logging.WithError(err).Errorf(c, "got transient error in ScheduleExecution")
			return
		}
		logging.WithError(err).Errorf(c, "got non-transient error in ScheduleExecution")
		origErr := err

		// put a and e to the transaction buffer, so that
		// FinishExecution.RollForward can see them.
		if err = ds.Put(c, a, e); err != nil {
			logging.WithError(err).Errorf(c, "putting attempt+execution for non-transient distributor error")
			return
		}
		return NewFinishExecutionAbnormal(
			eid, dm.AbnormalFinish_REJECTED,
			fmt.Sprintf("rejected during scheduling with non-transient error: %s", origErr),
		).RollForward(c)
	}

	if err = ResetExecutionTimeout(c, e); err != nil {
		logging.WithError(err).Errorf(c, "resetting timeout")
		return
	}

	if err = ds.Put(c, a, e); err != nil {
		logging.WithError(err).Errorf(c, "putting attempt+execution")
	}

	return
}
645120
func (s *scheduler) next() (interface{}, interface{}, bool) {
	s.mu.Lock()
	defer s.mu.Unlock()

	last := s.buckets[s.position]
	// Grab the first item in the bucket, move it to the end and return it.
	for k, v := range last {
		delete(last, k)
		s.buckets[s.at(-1)][k] = v
		return k, v, false
	}
	// The bucket was empty.  Advance to the next bucket.
	s.position = s.at(1)
	return nil, nil, true
}
362262
func (b *build) cancelScheduled(q *BuildQueue) int {
	numBuilds := b.numFolded()

	metrics.BuildQueueEntries.With(map[string]string{
		metrics.LabelBuildQueueName: q.name,
		metrics.LabelBuildState:     metrics.BuildStateWaiting,
	}).Sub(float64(numBuilds))

	b.reportStatus(q, false)

	return numBuilds
}
295719
func (c *Client) Enqueue(j *Job) error {
	return execEnqueue(j, c.pool)
}
1182812
func (c *Client) dequeuer() error {
	for {
		// acquire dequeue token
		select {
		case <-c.dequeueTokens:
			// continue
		case <-time.After(c.TokenTimeout):
			return c.die(ClientError, ErrTokenTimeout)
		case <-c.tomb.Dying():
			return tomb.ErrDying
		}

		// request next message
		msg, ack, err := c.backend.Dequeue(c)
		if err != nil {
			return c.die(BackendError, err)
		} else if msg == nil {
			return tomb.ErrDying
		}

		c.backend.Log(MessageDequeued, c, nil, msg, nil)

		// prepare publish packet
		publish := packet.NewPublish()
		publish.Message = *msg

		// set packet id
		if publish.Message.QOS > 0 {
			publish.ID = c.session.NextID()
		}

		// store packet if at least qos 1
		if publish.Message.QOS > 0 {
			err := c.session.SavePacket(session.Outgoing, publish)
			if err != nil {
				return c.die(SessionError, err)
			}
		}

		// acknowledge message
		if ack != nil {
			ack()

			c.backend.Log(MessageAcknowledged, c, nil, msg, nil)
		}

		// send packet
		err = c.send(publish, true)
		if err != nil {
			return c.die(TransportError, err)
		}

		// immediately put back dequeue token for qos 0 messages
		if publish.Message.QOS == 0 {
			select {
			case c.dequeueTokens <- struct{}{}:
			default:
				// continue if full for some reason
			}
		}

		c.backend.Log(MessageForwarded, c, nil, msg, nil)
	}
}
435627
func (m *MockSentPacketHandler) DequeuePacketForRetransmission() *ackhandler.Packet {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "DequeuePacketForRetransmission")
	ret0, _ := ret[0].(*ackhandler.Packet)
	return ret0
}
829925
func (w *watchQueue) Dequeue() (string, *kvdb.KVPair, error) {
	w.m.Lock()
	for {
		if w.updates.Len() > 0 {
			el := w.updates.Front()
			w.updates.Remove(el)
			w.m.Unlock()
			update := el.Value.(*watchUpdate)
			return update.key, update.kvp, update.err
		}
		w.cv.Wait()
	}
}
1069009
func (m *Meta) EnQueueDDLJob(job *model.Job) error {
	return m.enQueueDDLJob(m.jobListKey, job)
}
570511
func (c *TemplateInstanceFinalizerController) enqueue(templateInstance *templatev1.TemplateInstance) {
	key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(templateInstance)
	if err != nil {
		utilruntime.HandleError(fmt.Errorf("couldn't get key for object %#v: %v", templateInstance, err))
		return
	}

	c.queue.Add(key)
}
1242174
func (r *messageRing) Dequeue() (*Message, error) {
	r.mu.Lock()
	for len(r.queue) == 0 && !r.closed {
		r.wait.Wait()
	}

	if r.closed {
		r.mu.Unlock()
		return nil, errClosed
	}

	msg := r.queue[0]
	r.queue = r.queue[1:]
	r.sizeBytes -= int64(len(msg.Line))
	r.mu.Unlock()
	return msg, nil
}