// RescheduleInfo is used to calculate remaining reschedule attempts
// according to the given time and the task groups reschedule policy
344948
func (a Allocation) RescheduleInfo(t time.Time) (int, int) {
	var reschedulePolicy *ReschedulePolicy
	for _, tg := range a.Job.TaskGroups {
		if *tg.Name == a.TaskGroup {
			reschedulePolicy = tg.ReschedulePolicy
		}
	}
	if reschedulePolicy == nil {
		return 0, 0
	}
	availableAttempts := *reschedulePolicy.Attempts
	interval := *reschedulePolicy.Interval
	attempted := 0

	// Loop over reschedule tracker to find attempts within the restart policy's interval
	if a.RescheduleTracker != nil && availableAttempts > 0 && interval > 0 {
		for j := len(a.RescheduleTracker.Events) - 1; j >= 0; j-- {
			lastAttempt := a.RescheduleTracker.Events[j].RescheduleTime
			timeDiff := t.UTC().UnixNano() - lastAttempt
			if timeDiff < interval.Nanoseconds() {
				attempted += 1
			}
		}
	}
	return attempted, availableAttempts
}
147453
func (s *PutScheduledActionInput) SetSchedule(v string) *PutScheduledActionInput {
	s.Schedule = &v
	return s
}
968329
func (s *ScheduledAction) SetSchedule(v string) *ScheduledAction {
	s.Schedule = &v
	return s
}
885076
func (client *Client) DescribeScheduledTasks(args *DescribeScheduledTasksArgs) (tasks []ScheduledTaskItemType, pagination *common.PaginationResult, err error) {
	args.Validate()
	response := DescribeScheduledTasksResponse{}

	err = client.InvokeByFlattenMethod("DescribeScheduledTasks", args, &response)

	if err == nil {
		return response.ScheduledTasks.ScheduledTask, &response.PaginationResult, nil
	}

	return nil, nil, err
}
145543
func NewScheduler(poolID string, instance_id string, storageServer *storage.Server, cpDao dao.ControlPlane, facade *facade.Facade, pushreg *imgreg.RegistryListener, snapshotTTL int) (*scheduler, error) {
	s := &scheduler{
		cpDao:         cpDao,
		poolID:        poolID,
		instance_id:   instance_id,
		shutdown:      make(chan interface{}),
		stopped:       make(chan interface{}),
		zkleaderFunc:  Lead, // random scheduler implementation
		facade:        facade,
		snapshotTTL:   snapshotTTL,
		storageServer: storageServer,
		pushreg:       pushreg,
	}
	return s, nil
}
808210
func (s *Scheduler) Schedule(ctx context.Context) error {
	lastReport := s.Timer.Now()
	for {
		reportingDelay := time.Duration(atomic.LoadInt64(&s.ReportingDelayNs))
		wakeupTime := lastReport.Add(reportingDelay)
		now := s.Timer.Now()
		if now.After(wakeupTime) {
			wakeupTime = now.Add(reportingDelay)
			atomic.AddInt64(&s.stats.resetIntervalCounts, 1)
		}
		sleepTime := wakeupTime.Sub(now)

		atomic.AddInt64(&s.stats.scheduledSleepCounts, 1)
		select {
		case <-ctx.Done():
			return errors.Annotate(ctx.Err(), "context closed")
		case <-s.Timer.After(sleepTime):
			lastReport = s.Timer.Now()
			if err := errors.Annotate(s.ReportOnce(ctx), "failed reporting single metric"); err != nil {
				if err2 := errors.Annotate(s.ErrorHandler(err), "error handler returned an error"); err2 != nil {
					return err2
				}
			}
		}
	}
}
1194788
func RegisterVolumeSchedulingMetrics() {
	prometheus.MustRegister(VolumeBindingRequestSchedulerBinderCache)
	prometheus.MustRegister(VolumeSchedulingStageLatency)
	prometheus.MustRegister(VolumeSchedulingStageFailed)
}
248856
func (rki RevokedKeyInfo) ResetInfo() (keybase1.Seqno, bool) {
	return rki.resetSeqno, rki.isReset
}
179910
func (s *Service) PlanInfo(ctx context.Context, planIdentity string) (*Plan, error) {
	var plan Plan
	return &plan, s.Get(ctx, &plan, fmt.Sprintf("/plans/%v", planIdentity), nil, nil)
}
719199
func (s *BatchServiceStateManager) WaitScheduled(tenantID string, serviceIDs ...string) {
	s.lock.RLock()
	var wg sync.WaitGroup
	for _, sid := range serviceIDs {
		// find the service in the queues
		if svc, ok := s.findService(tenantID, sid); ok {
			wg.Add(1)
			go func(cs *CancellableService) {
				<-cs.C
				wg.Done()
			}(svc)
		} else {
			plog.WithFields(logrus.Fields{
				"tenantid":  tenantID,
				"serviceid": sid,
			}).Debug("Not waiting for service, could not find it")
		}
	}
	s.lock.RUnlock()
	wg.Wait()
}
721893
func (a *Allocation) NextDelay() time.Duration {
	policy := a.ReschedulePolicy()
	// Can be nil if the task group was updated to remove its reschedule policy
	if policy == nil {
		return 0
	}
	delayDur := policy.Delay
	if a.RescheduleTracker == nil || a.RescheduleTracker.Events == nil || len(a.RescheduleTracker.Events) == 0 {
		return delayDur
	}
	events := a.RescheduleTracker.Events
	switch policy.DelayFunction {
	case "exponential":
		delayDur = a.RescheduleTracker.Events[len(a.RescheduleTracker.Events)-1].Delay * 2
	case "fibonacci":
		if len(events) >= 2 {
			fibN1Delay := events[len(events)-1].Delay
			fibN2Delay := events[len(events)-2].Delay
			// Handle reset of delay ceiling which should cause
			// a new series to start
			if fibN2Delay == policy.MaxDelay && fibN1Delay == policy.Delay {
				delayDur = fibN1Delay
			} else {
				delayDur = fibN1Delay + fibN2Delay
			}
		}
	default:
		return delayDur
	}
	if policy.MaxDelay > 0 && delayDur > policy.MaxDelay {
		delayDur = policy.MaxDelay
		// check if delay needs to be reset

		lastRescheduleEvent := a.RescheduleTracker.Events[len(a.RescheduleTracker.Events)-1]
		timeDiff := a.LastEventTime().UTC().UnixNano() - lastRescheduleEvent.RescheduleTime
		if timeDiff > delayDur.Nanoseconds() {
			delayDur = policy.Delay
		}

	}

	return delayDur
}
87553
func (s *RemindersService) Info(reminder string) *RemindersInfoCall {
	var call RemindersInfoCall
	call.service = s
	call.reminder = reminder
	return &call
}
1130584
func NewServiceScheduler(logger log.Logger, state State, planner Planner) Scheduler {
	s := &GenericScheduler{
		logger:  logger.Named("service_sched"),
		state:   state,
		planner: planner,
		batch:   false,
	}
	return s
}
1197753
func updateByReschedulable(alloc *structs.Allocation, now time.Time, evalID string, d *structs.Deployment) (rescheduleNow, rescheduleLater bool, rescheduleTime time.Time) {
	// If the allocation is part of an ongoing active deployment, we only allow it to reschedule
	// if it has been marked eligible
	if d != nil && alloc.DeploymentID == d.ID && d.Active() && !alloc.DesiredTransition.ShouldReschedule() {
		return
	}

	// Check if the allocation is marked as it should be force rescheduled
	if alloc.DesiredTransition.ShouldForceReschedule() {
		rescheduleNow = true
	}

	// Reschedule if the eval ID matches the alloc's followup evalID or if its close to its reschedule time
	rescheduleTime, eligible := alloc.NextRescheduleTime()
	if eligible && (alloc.FollowupEvalID == evalID || rescheduleTime.Sub(now) <= rescheduleWindowSize) {
		rescheduleNow = true
		return
	}
	if eligible && alloc.FollowupEvalID == "" {
		rescheduleLater = true
	}
	return
}
744300
func (db *AgendaDB) AgendaInfo(agendaID string) (*AgendaTagged, error) {
	if db == nil || db.sdb == nil {
		return nil, errDefault
	}

	agenda, err := db.loadAgenda(agendaID)
	if err != nil {
		return nil, err
	}

	return agenda, nil
}
627706
func NewSchedule(ctx ttnlog.Interface) Schedule {
	s := &schedule{
		ctx:                   ctx,
		items:                 make(map[string]*scheduledItem),
		downlinkSubscriptions: make(map[string]chan *router_pb.DownlinkMessage),
	}
	go func() {
		for {
			<-time.After(10 * time.Second)
			s.RLock()
			numItems := len(s.items)
			s.RUnlock()
			if numItems > 0 {
				s.Lock()
				for id, item := range s.items {
					// Delete the item if we are more than 2 seconds after the deadline
					if time.Now().After(item.deadlineAt.Add(2 * time.Second)) {
						delete(s.items, id)
					}
				}
				s.Unlock()
			}
		}
	}()
	return s
}
399979
func (s *CreateCrawlerInput) SetSchedule(v string) *CreateCrawlerInput {
	s.Schedule = &v
	return s
}