// Enters a job into the cron schedule, without actually starting the job.
// If the job is already present in the schedule, this will update the schedule entry with the new
// configuration.
// 
// Parameters:
//  - Description
353078
func (p *AuroraSchedulerManagerClient) ScheduleCronJob(ctx context.Context, description *JobConfiguration) (r *Response, err error) {
  var _args133 AuroraSchedulerManagerScheduleCronJobArgs
  _args133.Description = description
  var _result134 AuroraSchedulerManagerScheduleCronJobResult
  if err = p.Client_().Call(ctx, "scheduleCronJob", &_args133, &_result134); err != nil {
    return
  }
  return _result134.GetSuccess(), nil
}
580463
func (e *Enqueuer) EnqueueIn(jobName string, secondsFromNow int64, args map[string]interface{}) (*ScheduledJob, error) {
	job := &Job{
		Name:       jobName,
		ID:         makeIdentifier(),
		EnqueuedAt: nowEpochSeconds(),
		Args:       args,
	}

	rawJSON, err := job.serialize()
	if err != nil {
		return nil, err
	}

	conn := e.Pool.Get()
	defer conn.Close()

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

	_, err = conn.Do("ZADD", redisKeyScheduled(e.Namespace), scheduledJob.RunAt, rawJSON)
	if err != nil {
		return nil, err
	}

	if err := e.addToKnownJobs(conn, jobName); err != nil {
		return scheduledJob, err
	}

	return scheduledJob, nil
}
302862
func (j *Job) Saturday() (job *Job) {
	if j.interval != 1 {
		panic("")
	}
	j.startDay = 6
	job = j.Weeks()
	return
}
1176052
func (l *ListTask) Entry(update string) {
	l.ch <- &Update{
		S:  fmt.Sprintf("%s\n", update),
		At: time.Now(),
	}
}
355060
func (c *FakeCronJobs) Update(cronJob *v2alpha1.CronJob) (result *v2alpha1.CronJob, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewUpdateAction(cronjobsResource, c.ns, cronJob), &v2alpha1.CronJob{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v2alpha1.CronJob), err
}
767195
func (e *engineImpl) execCronTickTask(c context.Context, tqTask proto.Message) error {
	msg := tqTask.(*internal.CronTickTask)
	return e.jobTxn(c, msg.JobId, func(c context.Context, job *Job, isNew bool) error {
		if isNew {
			logging.Errorf(c, "Scheduled job is unexpectedly gone")
			return errSkipPut
		}
		logging.Infof(c, "Tick %d has arrived", msg.TickNonce)
		return pokeCron(c, job, e.cfg.Dispatcher, func(m *cron.Machine) error {
			// OnTimerTick returns an error if the tick happened too soon. Mark this
			// error as transient to trigger task queue retry at a later time.
			return transient.Tag.Apply(m.OnTimerTick(msg.TickNonce))
		})
	})
}
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
				}
			}
		}
	}
}
1275144
func In(duration time.Duration, job cron.Job) {
	go func() {
		time.Sleep(duration)
		New(job).Run()
	}()
}
946328
func (op *Operator) SchedulerGetConfiguration(args *structs.GenericRequest, reply *structs.SchedulerConfigurationResponse) error {
	if done, err := op.srv.forward("Operator.SchedulerGetConfiguration", args, args, reply); done {
		return err
	}

	// This action requires operator read access.
	rule, err := op.srv.ResolveToken(args.AuthToken)
	if err != nil {
		return err
	} else if rule != nil && !rule.AllowOperatorRead() {
		return structs.ErrPermissionDenied
	}

	state := op.srv.fsm.State()
	index, config, err := state.SchedulerConfig()

	if err != nil {
		return err
	} else if config == nil {
		return fmt.Errorf("scheduler config not initialized yet")
	}

	reply.SchedulerConfig = config
	reply.QueryMeta.Index = index
	op.srv.setQueryMeta(&reply.QueryMeta)

	return nil
}
118335
func Scheduler(c context.Context, cfg *pb.ProjectConfig) error {
	// Sort jobs by ID.
	sort.Slice(cfg.Job, func(i, j int) bool {
		return cfg.Job[i].Id < cfg.Job[j].Id
	})
	sort.Slice(cfg.Trigger, func(i, j int) bool {
		return cfg.Trigger[i].Id < cfg.Trigger[j].Id
	})

	// ACL set name => list of ACLs.
	aclSets := make(map[string][]*pb.Acl)
	for _, s := range cfg.AclSets {
		aclSets[s.Name] = s.Acls
	}

	// Expand ACL sets.
	for _, x := range cfg.Job {
		x.Acls = normalizeACLs(x.Acls, x.AclSets, aclSets)
		x.AclSets = nil
	}
	for _, x := range cfg.Trigger {
		x.Acls = normalizeACLs(x.Acls, x.AclSets, aclSets)
		x.AclSets = nil
	}
	cfg.AclSets = nil

	// Normalize triggers.
	for _, x := range cfg.Trigger {
		sort.Strings(x.Triggers)
		if gt := x.Gitiles; gt != nil {
			for i, r := range gt.Refs {
				if !strings.HasPrefix(r, "regexp:") {
					gt.Refs[i] = "regexp:" + regexp.QuoteMeta(r)
				}
			}
			sort.Strings(gt.Refs)
		}
	}

	return nil
}
945620
func (e *engineImpl) updateJob(c context.Context, def catalog.Definition) error {
	return e.jobTxn(c, def.JobID, func(c context.Context, job *Job, isNew bool) error {
		if !isNew && job.Enabled && job.MatchesDefinition(def) {
			return errSkipPut
		}

		if isNew {
			// JobID is <projectID>/<name>, it's ensured by Catalog.
			chunks := strings.Split(def.JobID, "/")
			if len(chunks) != 2 {
				return fmt.Errorf("unexpected jobID format: %s", def.JobID)
			}
			*job = Job{
				JobID:               def.JobID,
				ProjectID:           chunks[0],
				Flavor:              def.Flavor,
				Enabled:             false, // to trigger 'if wasDisabled' below
				Schedule:            def.Schedule,
				Task:                def.Task,
				TriggeringPolicyRaw: def.TriggeringPolicy,
				TriggeredJobIDs:     def.TriggeredJobIDs,
			}
		}
		wasDisabled := !job.Enabled
		oldEffectiveSchedule := job.EffectiveSchedule()
		oldTriggeringPolicy := job.TriggeringPolicyRaw

		// Update the job in full before running any state changes.
		job.Flavor = def.Flavor
		job.Revision = def.Revision
		job.RevisionURL = def.RevisionURL
		job.Acls = def.Acls
		job.Enabled = true
		job.Schedule = def.Schedule
		job.Task = def.Task
		job.TriggeringPolicyRaw = def.TriggeringPolicy
		job.TriggeredJobIDs = def.TriggeredJobIDs

		// If job triggering policy has changed, schedule a triage to potentially
		// act based on the new policy.
		if !bytes.Equal(oldTriggeringPolicy, job.TriggeringPolicyRaw) {
			logging.Infof(c, "Job's triggering policy has changed, scheduling a triage")
			if err := e.kickTriageLater(c, job.JobID, 0); err != nil {
				return err
			}
		}

		// If the job was just enabled or its schedule changed, poke the cron
		// machine to potentially schedule a new tick.
		return pokeCron(c, job, e.cfg.Dispatcher, func(m *cron.Machine) error {
			if wasDisabled {
				m.Enable()
			}
			if job.EffectiveSchedule() != oldEffectiveSchedule {
				logging.Infof(c, "Job's schedule changed: %q -> %q", job.EffectiveSchedule(), oldEffectiveSchedule)
				m.OnScheduleChange()
			}
			return nil
		})
	})
}
198798
func (r *EtcdRegistry) Schedule() ([]job.ScheduledUnit, error) {
	key := r.prefixed(jobPrefix)
	opts := &etcd.GetOptions{
		Sort:      true,
		Recursive: true,
	}
	res, err := r.kAPI.Get(context.Background(), key, opts)
	if err != nil {
		if isEtcdError(err, etcd.ErrorCodeKeyNotFound) {
			err = nil
		}
		return nil, err
	}

	heartbeats := make(map[string]string)
	uMap := make(map[string]*job.ScheduledUnit)

	for _, dir := range res.Node.Nodes {
		_, name := path.Split(dir.Key)
		u := &job.ScheduledUnit{
			Name:            name,
			TargetMachineID: dirToTargetMachineID(dir),
		}
		heartbeats[name] = dirToHeartbeat(dir)
		uMap[name] = u
	}

	states, err := r.statesByMUSKey()
	if err != nil {
		return nil, err
	}

	var sortable sort.StringSlice

	// Determine the JobState of each ScheduledUnit
	for name, su := range uMap {
		sortable = append(sortable, name)
		key := MUSKey{
			MachID: su.TargetMachineID,
			Name:   name,
		}
		us := states[key]
		js := determineJobState(heartbeats[name], su.TargetMachineID, us)
		su.State = &js
	}
	sortable.Sort()

	units := make([]job.ScheduledUnit, 0, len(sortable))
	for _, name := range sortable {
		units = append(units, *uMap[name])
	}
	return units, nil
}
108022
func (j *Job) Thursday() (job *Job) {
	if j.interval != 1 {
		panic("")
	}
	j.startDay = 4
	job = j.Weeks()
	return
}
972157
func (g *genericScheduler) Schedule(pod *v1.Pod, nodeLister algorithm.NodeLister) (result ScheduleResult, err error) {
	trace := utiltrace.New(fmt.Sprintf("Scheduling %s/%s", pod.Namespace, pod.Name))
	defer trace.LogIfLong(100 * time.Millisecond)

	if err := podPassesBasicChecks(pod, g.pvcLister); err != nil {
		return result, err
	}

	nodes, err := nodeLister.List()
	if err != nil {
		return result, err
	}
	if len(nodes) == 0 {
		return result, ErrNoNodesAvailable
	}

	if err := g.snapshot(); err != nil {
		return result, err
	}

	trace.Step("Computing predicates")
	startPredicateEvalTime := time.Now()
	filteredNodes, failedPredicateMap, err := g.findNodesThatFit(pod, nodes)
	if err != nil {
		return result, err
	}

	if len(filteredNodes) == 0 {
		return result, &FitError{
			Pod:              pod,
			NumAllNodes:      len(nodes),
			FailedPredicates: failedPredicateMap,
		}
	}
	metrics.SchedulingAlgorithmPredicateEvaluationDuration.Observe(metrics.SinceInSeconds(startPredicateEvalTime))
	metrics.DeprecatedSchedulingAlgorithmPredicateEvaluationDuration.Observe(metrics.SinceInMicroseconds(startPredicateEvalTime))
	metrics.SchedulingLatency.WithLabelValues(metrics.PredicateEvaluation).Observe(metrics.SinceInSeconds(startPredicateEvalTime))
	metrics.DeprecatedSchedulingLatency.WithLabelValues(metrics.PredicateEvaluation).Observe(metrics.SinceInSeconds(startPredicateEvalTime))

	trace.Step("Prioritizing")
	startPriorityEvalTime := time.Now()
	// When only one node after predicate, just use it.
	if len(filteredNodes) == 1 {
		metrics.SchedulingAlgorithmPriorityEvaluationDuration.Observe(metrics.SinceInSeconds(startPriorityEvalTime))
		metrics.DeprecatedSchedulingAlgorithmPriorityEvaluationDuration.Observe(metrics.SinceInMicroseconds(startPriorityEvalTime))
		return ScheduleResult{
			SuggestedHost:  filteredNodes[0].Name,
			EvaluatedNodes: 1 + len(failedPredicateMap),
			FeasibleNodes:  1,
		}, nil
	}

	metaPrioritiesInterface := g.priorityMetaProducer(pod, g.nodeInfoSnapshot.NodeInfoMap)
	priorityList, err := PrioritizeNodes(pod, g.nodeInfoSnapshot.NodeInfoMap, metaPrioritiesInterface, g.prioritizers, filteredNodes, g.extenders)
	if err != nil {
		return result, err
	}
	metrics.SchedulingAlgorithmPriorityEvaluationDuration.Observe(metrics.SinceInSeconds(startPriorityEvalTime))
	metrics.DeprecatedSchedulingAlgorithmPriorityEvaluationDuration.Observe(metrics.SinceInMicroseconds(startPriorityEvalTime))
	metrics.SchedulingLatency.WithLabelValues(metrics.PriorityEvaluation).Observe(metrics.SinceInSeconds(startPriorityEvalTime))
	metrics.DeprecatedSchedulingLatency.WithLabelValues(metrics.PriorityEvaluation).Observe(metrics.SinceInSeconds(startPriorityEvalTime))

	trace.Step("Selecting host")

	host, err := g.selectHost(priorityList)
	return ScheduleResult{
		SuggestedHost:  host,
		EvaluatedNodes: len(filteredNodes) + len(failedPredicateMap),
		FeasibleNodes:  len(filteredNodes),
	}, err
}
220752
func parseCronSchedule(expr string, randSeed uint64) (*Schedule, error) {
	cronexprLock.Lock()
	exp, err := cronexpr.Parse(expr)
	cronexprLock.Unlock()
	if err != nil {
		return nil, err
	}
	return &Schedule{cronExpr: exp}, nil
}
333665
func (s *CreateSnapshotScheduleInput) SetScheduleDescription(v string) *CreateSnapshotScheduleInput {
	s.ScheduleDescription = &v
	return s
}
987944
func (p *ReadOnlySchedulerClient) PopulateJobConfig(ctx context.Context, description *JobConfiguration) (r *Response, err error) {
  var _args68 ReadOnlySchedulerPopulateJobConfigArgs
  _args68.Description = description
  var _result69 ReadOnlySchedulerPopulateJobConfigResult
  if err = p.Client_().Call(ctx, "populateJobConfig", &_args68, &_result69); err != nil {
    return
  }
  return _result69.GetSuccess(), nil
}