// NextRescheduleTime returns a time on or after which the allocation is eligible to be rescheduled,
// and whether the next reschedule time is within policy's interval if the policy doesn't allow unlimited reschedules
192258
func (a *Allocation) NextRescheduleTime() (time.Time, bool) {
	failTime := a.LastEventTime()
	reschedulePolicy := a.ReschedulePolicy()
	if a.DesiredStatus == AllocDesiredStatusStop || a.ClientStatus != AllocClientStatusFailed || failTime.IsZero() || reschedulePolicy == nil {
		return time.Time{}, false
	}

	nextDelay := a.NextDelay()
	nextRescheduleTime := failTime.Add(nextDelay)
	rescheduleEligible := reschedulePolicy.Unlimited || (reschedulePolicy.Attempts > 0 && a.RescheduleTracker == nil)
	if reschedulePolicy.Attempts > 0 && a.RescheduleTracker != nil && a.RescheduleTracker.Events != nil {
		// Check for eligibility based on the interval if max attempts is set
		attempted := 0
		for j := len(a.RescheduleTracker.Events) - 1; j >= 0; j-- {
			lastAttempt := a.RescheduleTracker.Events[j].RescheduleTime
			timeDiff := failTime.UTC().UnixNano() - lastAttempt
			if timeDiff < reschedulePolicy.Interval.Nanoseconds() {
				attempted += 1
			}
		}
		rescheduleEligible = attempted < reschedulePolicy.Attempts && nextDelay < reschedulePolicy.Interval
	}
	return nextRescheduleTime, rescheduleEligible
}
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
				}
			}
		}
	}
}
114180
func (s *CreateMaintenanceWindowInput) SetSchedule(v string) *CreateMaintenanceWindowInput {
	s.Schedule = &v
	return s
}
288449
func (s *Crawler) SetSchedule(v *Schedule) *Crawler {
	s.Schedule = v
	return s
}
675393
func HandleScheduleNextQueueItem(ds storage.DeviceSession, mode storage.DeviceMode) error {
	ctx := dataContext{
		DeviceMode:    mode,
		DeviceSession: ds,
	}

	for _, t := range scheduleNextQueueItemTasks {
		if err := t(&ctx); err != nil {
			if err == ErrAbort {
				return nil
			}
			return err
		}
	}

	return nil
}
83128
func (w *WorkerConfig) scheduler() {
	pollSets := []string{w.nsKey("retry"), w.nsKey("schedule")}

	for _ = range time.Tick(w.PollInterval) {
		w.RLock() // don't let quitHandler() stop us in the middle of a run
		conn := w.RedisPool.Get()
		now := fmt.Sprintf("%f", timeFloat(time.Now()))
		for _, set := range pollSets {
			conn.Send("MULTI")
			conn.Send("ZRANGEBYSCORE", set, "-inf", now)
			conn.Send("ZREMRANGEBYSCORE", set, "-inf", now)
			res, err := redis.Values(conn.Do("EXEC"))
			if err != nil {
				w.handleError(err)
				continue
			}

			for _, msg := range res[0].([]interface{}) {
				parsedMsg := &struct {
					Queue string `json:"queue"`
				}{}
				msgBytes := msg.([]byte)
				err := json.Unmarshal(msgBytes, parsedMsg)
				if err != nil {
					w.handleError(err)
					continue
				}
				if _, err = conn.Do("RPUSH", w.nsKey("queue:"+parsedMsg.Queue), msgBytes); err != nil {
					w.handleError(err)
				}
			}
		}
		conn.Close()
		w.RUnlock()
	}
}
413354
func (t *TimeTable) NearestTime(index uint64) time.Time {
	t.l.RLock()
	defer t.l.RUnlock()

	n := len(t.table)
	idx := sort.Search(n, func(i int) bool {
		return t.table[i].Index <= index
	})
	if idx < n && idx >= 0 {
		return t.table[idx].Time
	}
	return time.Time{}
}
181168
func Schedule(d time.Duration, fn func(), r Recovery) Canceler {
	s := &scheduler{
		d:     d,
		fn:    fn,
		r:     r,
		state: 1,
	}
	s.timer = time.AfterFunc(d, s.schedule)
	return s
}
1072750
func (c *crontime) nextValidHour(baseTime time.Time) {
	for _, hour := range c.hour {
		if c.calculatedTime.Day() == baseTime.Day() {
			if !hasPassed(hour, c.calculatedTime.Hour()) {
				c.calculatedTime = setHour(c.calculatedTime, hour)
				return
			}
		} else {
			c.calculatedTime = setHour(c.calculatedTime, hour)
			return
		}
	}
	// If no result was found try it again in the following day.
	c.calculatedTime = c.calculatedTime.AddDate(0, 0, 1)    // <-|
	c.calculatedTime = setHour(c.calculatedTime, c.hour[0]) //   |
	//log.Println("Cronbee: Hour", c.calculatedTime, baseTime) // |
	c.nextValidMonth(baseTime) // May trigger a new month --------|
	c.nextValidDay(baseTime)
	c.nextValidHour(baseTime)
}
1040996
func NewSchedule(clock clock.Clock) *Schedule {
	return &Schedule{
		time: clock,
		m:    make(map[interface{}]*scheduleItem),
	}
}
1374714
func (s *TreatmentResource) SetSchedule(v *Schedule) *TreatmentResource {
	s.Schedule = v
	return s
}
884734
func NewCronSchedule(entry string) *CronSchedule {
	schedule := cron.New()
	return &CronSchedule{
		entry:    entry,
		schedule: schedule,
		enabled:  false,
	}
}
1315147
func NewScheduler() *InMemory {
	return &InMemory{
		addCh:   make(chan *Entry),
		stopCh:  make(chan struct{}),
		entries: nil,
	}
}
381
func (s *GetMaintenanceWindowOutput) SetScheduleTimezone(v string) *GetMaintenanceWindowOutput {
	s.ScheduleTimezone = &v
	return s
}
798098
func (s *GetMaintenanceWindowOutput) SetSchedule(v string) *GetMaintenanceWindowOutput {
	s.Schedule = &v
	return s
}
769625
func (s *InventoryConfiguration) SetSchedule(v *InventorySchedule) *InventoryConfiguration {
	s.Schedule = v
	return s
}
1068542
func (s *CreateSnapshotScheduleOutput) SetScheduleDefinitions(v []*string) *CreateSnapshotScheduleOutput {
	s.ScheduleDefinitions = v
	return s
}