// oneTimeJobSchedule returns a storagetransfer job schedule that will only be executed one
765031
func oneTimeJobSchedule(ts time.Time) *storagetransfer.Schedule {
	date := toDate(ts)
	return &storagetransfer.Schedule{
		ScheduleEndDate:   date,
		ScheduleStartDate: date,
	}
}
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
}
66722
func NewScheduler(
	numScrapers int,
	l *zap.Logger,
	targets platform.ScraperTargetStoreService,
	p nats.Publisher,
	s nats.Subscriber,
	interval time.Duration,
	timeout time.Duration,
) (*Scheduler, error) {
	if interval == 0 {
		interval = 60 * time.Second
	}
	if timeout == 0 {
		timeout = 30 * time.Second
	}
	scheduler := &Scheduler{
		Targets:   targets,
		Interval:  interval,
		Timeout:   timeout,
		Publisher: p,
		Logger:    l,
		gather:    make(chan struct{}, 100),
	}

	for i := 0; i < numScrapers; i++ {
		err := s.Subscribe(promTargetSubject, "", &handler{
			Scraper:   new(prometheusScraper),
			Publisher: p,
			Logger:    l,
		})
		if err != nil {
			return nil, err
		}
	}

	return scheduler, nil
}
1330890
func (ctl *Controller) LaunchJob(c context.Context, j *JobConfig) (JobID, error) {
	disp := ctl.tq()

	if err := j.Validate(); err != nil {
		return 0, errors.Annotate(err, "bad job config").Err()
	}
	if _, err := ctl.getFactory(j.Mapper); err != nil {
		return 0, errors.Annotate(err, "bad job config").Err()
	}

	// Prepare and store the job entity, generate its key. Launch a tq task that
	// subdivides the key space and launches individual shards. We do it
	// asynchronously since this can be potentially slow (for large number of
	// shards).
	var job Job
	err := runTxn(c, func(c context.Context) error {
		now := clock.Now(c).UTC()
		job = Job{
			Config:  *j,
			State:   State_STARTING,
			Created: now,
			Updated: now,
		}
		if err := datastore.Put(c, &job); err != nil {
			return errors.Annotate(err, "failed to store Job entity").Tag(transient.Tag).Err()
		}
		return disp.AddTask(c, &tq.Task{
			Title: fmt.Sprintf("split:job-%d", job.ID),
			Payload: &tasks.SplitAndLaunch{
				JobId: int64(job.ID),
			},
		})
	})
	if err != nil {
		return 0, err
	}
	return job.ID, nil
}
131614
func ScheduleUnmarshalJSON(b []byte) (schedule Schedule, err error) {
	var mixed interface{}
	json.Unmarshal(b, &mixed)

	for key, value := range mixed.(map[string]interface{}) {
		rawValue, _ := json.Marshal(value)
		switch key {
		case "date":
			var date Date
			err = json.Unmarshal(rawValue, &date)
			schedule = date
		case "day":
			var day Day
			err = json.Unmarshal(rawValue, &day)
			schedule = day
		case "intersection":
			var intersection Intersection
			err = json.Unmarshal(rawValue, &intersection)
			schedule = intersection
		case "month":
			var month Month
			err = json.Unmarshal(rawValue, &month)
			schedule = month
		case "union":
			var union Union
			err = json.Unmarshal(rawValue, &union)
			schedule = union
		case "week":
			var week Week
			err = json.Unmarshal(rawValue, &week)
			schedule = week
		case "weekday":
			var weekday Weekday
			err = json.Unmarshal(rawValue, &weekday)
			schedule = weekday
		case "year":
			var year Year
			err = json.Unmarshal(rawValue, &year)
			schedule = year
		default:
			err = fmt.Errorf("%s is not a recognized schedule", key)
		}
	}
	return
}
775741
func (cli *OpsGenieClient) Schedule() (*OpsGenieScheduleClient, error) {
	cli.makeHTTPTransportSettings()

	scheduleClient := new(OpsGenieScheduleClient)
	scheduleClient.SetOpsGenieClient(*cli)

	if cli.opsGenieAPIURL == "" {
		scheduleClient.SetOpsGenieAPIUrl(endpointURL)
	}

	return scheduleClient, nil
}
575626
func newScheduler(idx uint) *scheduler {
	return &scheduler{
		bit:       idx,
		responses: make(map[uint64]*response),
	}
}
736545
func getNextJobs(n int, poolId string) ([]*Job, error) {
	// Start a new transaction
	t := newTransaction()
	// Invoke a script to get all the jobs which are ready to execute based on their
	// time parameter and whether or not they are in the queued set.
	jobs := []*Job{}
	t.popNextJobs(n, poolId, newScanJobsHandler(&jobs))

	// Execute the transaction
	if err := t.exec(); err != nil {
		return nil, err
	}
	return jobs, nil
}
633612
func newJobs(c *BatchV1Client, namespace string) *jobs {
	return &jobs{
		client: c.RESTClient(),
		ns:     namespace,
	}
}
328014
func (s *SystemScheduler) computeJobAllocs() error {
	// Lookup the allocations by JobID
	ws := memdb.NewWatchSet()
	allocs, err := s.state.AllocsByJob(ws, s.eval.Namespace, s.eval.JobID, true)
	if err != nil {
		return fmt.Errorf("failed to get allocs for job '%s': %v",
			s.eval.JobID, err)
	}

	// Determine the tainted nodes containing job allocs
	tainted, err := taintedNodes(s.state, allocs)
	if err != nil {
		return fmt.Errorf("failed to get tainted nodes for job '%s': %v",
			s.eval.JobID, err)
	}

	// Update the allocations which are in pending/running state on tainted
	// nodes to lost
	updateNonTerminalAllocsToLost(s.plan, tainted, allocs)

	// Filter out the allocations in a terminal state
	allocs, terminalAllocs := structs.FilterTerminalAllocs(allocs)

	// Diff the required and existing allocations
	diff := diffSystemAllocs(s.job, s.nodes, tainted, allocs, terminalAllocs)
	s.logger.Debug("reconciled current state with desired state",
		"place", len(diff.place), "update", len(diff.update),
		"migrate", len(diff.migrate), "stop", len(diff.stop),
		"ignore", len(diff.ignore), "lost", len(diff.lost))

	// Add all the allocs to stop
	for _, e := range diff.stop {
		s.plan.AppendStoppedAlloc(e.Alloc, allocNotNeeded, "")
	}

	// Add all the allocs to migrate
	for _, e := range diff.migrate {
		s.plan.AppendStoppedAlloc(e.Alloc, allocNodeTainted, "")
	}

	// Lost allocations should be transitioned to desired status stop and client
	// status lost.
	for _, e := range diff.lost {
		s.plan.AppendStoppedAlloc(e.Alloc, allocLost, structs.AllocClientStatusLost)
	}

	// Attempt to do the upgrades in place
	destructiveUpdates, inplaceUpdates := inplaceUpdate(s.ctx, s.eval, s.job, s.stack, diff.update)
	diff.update = destructiveUpdates

	if s.eval.AnnotatePlan {
		s.plan.Annotations = &structs.PlanAnnotations{
			DesiredTGUpdates: desiredUpdates(diff, inplaceUpdates, destructiveUpdates),
		}
	}

	// Check if a rolling upgrade strategy is being used
	limit := len(diff.update)
	if !s.job.Stopped() && s.job.Update.Rolling() {
		limit = s.job.Update.MaxParallel
	}

	// Treat non in-place updates as an eviction and new placement.
	s.limitReached = evictAndPlace(s.ctx, diff, diff.update, allocUpdating, &limit)

	// Nothing remaining to do if placement is not required
	if len(diff.place) == 0 {
		if !s.job.Stopped() {
			for _, tg := range s.job.TaskGroups {
				s.queuedAllocs[tg.Name] = 0
			}
		}
		return nil
	}

	// Record the number of allocations that needs to be placed per Task Group
	for _, allocTuple := range diff.place {
		s.queuedAllocs[allocTuple.TaskGroup.Name] += 1
	}

	// Compute the placements
	return s.computePlacements(diff.place)
}
451499
func (schedule Schedule) GetScheduleTime() *time.Time {
	if scheduleTime := schedule.ScheduleTime; scheduleTime != nil {
		if scheduleTime.After(time.Now().Add(time.Minute)) {
			return scheduleTime
		}
	}
	return nil
}
1008081
func (j *Job) BatchDeregister(args *structs.JobBatchDeregisterRequest, reply *structs.JobBatchDeregisterResponse) error {
	if done, err := j.srv.forward("Job.BatchDeregister", args, args, reply); done {
		return err
	}
	defer metrics.MeasureSince([]string{"nomad", "job", "batch_deregister"}, time.Now())

	// Resolve the ACL token
	aclObj, err := j.srv.ResolveToken(args.AuthToken)
	if err != nil {
		return err
	}

	// Validate the arguments
	if len(args.Jobs) == 0 {
		return fmt.Errorf("given no jobs to deregister")
	}
	if len(args.Evals) != 0 {
		return fmt.Errorf("evaluations should not be populated")
	}

	// Loop through checking for permissions
	for jobNS := range args.Jobs {
		// Check for submit-job permissions
		if aclObj != nil && !aclObj.AllowNsOp(jobNS.Namespace, acl.NamespaceCapabilitySubmitJob) {
			return structs.ErrPermissionDenied
		}
	}

	// Grab a snapshot
	snap, err := j.srv.fsm.State().Snapshot()
	if err != nil {
		return err
	}

	// Loop through to create evals
	for jobNS, options := range args.Jobs {
		if options == nil {
			return fmt.Errorf("no deregister options provided for %v", jobNS)
		}

		job, err := snap.JobByID(nil, jobNS.Namespace, jobNS.ID)
		if err != nil {
			return err
		}

		// If the job is periodic or parameterized, we don't create an eval.
		if job != nil && (job.IsPeriodic() || job.IsParameterized()) {
			continue
		}

		priority := structs.JobDefaultPriority
		jtype := structs.JobTypeService
		if job != nil {
			priority = job.Priority
			jtype = job.Type
		}

		// Create a new evaluation
		eval := &structs.Evaluation{
			ID:          uuid.Generate(),
			Namespace:   jobNS.Namespace,
			Priority:    priority,
			Type:        jtype,
			TriggeredBy: structs.EvalTriggerJobDeregister,
			JobID:       jobNS.ID,
			Status:      structs.EvalStatusPending,
		}
		args.Evals = append(args.Evals, eval)
	}

	// Commit this update via Raft
	_, index, err := j.srv.raftApply(structs.JobBatchDeregisterRequestType, args)
	if err != nil {
		j.logger.Error("batch deregister failed", "error", err)
		return err
	}

	reply.Index = index
	return nil
}
884734
func NewCronSchedule(entry string) *CronSchedule {
	schedule := cron.New()
	return &CronSchedule{
		entry:    entry,
		schedule: schedule,
		enabled:  false,
	}
}
284581
func (s *SQLStore) scheduleSubStoreFlush(ss *SQLSubStore) {
	needSignal := false
	f := s.ssFlusher
	f.Lock()
	f.stores[ss] = struct{}{}
	if !f.signaled {
		f.signaled = true
		needSignal = true
	}
	f.Unlock()
	if needSignal {
		select {
		case f.signalCh <- struct{}{}:
		default:
		}
	}
}
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
}
823618
func NewBatchScheduler(logger log.Logger, state State, planner Planner) Scheduler {
	s := &GenericScheduler{
		logger:  logger.Named("batch_sched"),
		state:   state,
		planner: planner,
		batch:   true,
	}
	return s
}
795909
func (c *Client) RunJobDetached(appID string, req *ct.NewJob) (*ct.Job, error) {
	job := &ct.Job{}
	return job, c.Post(fmt.Sprintf("/apps/%s/jobs", appID), req, job)
}