// Cron executes scheduled tasks
// TODO: if closing Timers'count in single cron call more than timerBacklog will case problem.
489722
func Cron() {
	now := time.Now()
	unn := now.UnixNano()
	Manager.timers.Range(func(idInterface, tInterface interface{}) bool {
		t := tInterface.(*Timer)
		id := idInterface.(int64)
		// prevent ChClosingTimer exceed
		if t.counter == 0 {
			if len(Manager.ChClosingTimer) < timerBacklog {
				t.Stop()
			}
			return true
		}

		// condition timer
		if t.condition != nil {
			if t.condition.Check(now) {
				pexec(id, t.fn)
			}
			return true
		}

		// execute job
		if t.createAt+t.elapse <= unn {
			pexec(id, t.fn)
			t.elapse += int64(t.interval)

			// update timer counter
			if t.counter != LoopForever && t.counter > 0 {
				t.counter--
			}
		}
		return true
	})
}
748921
func (c *Cron) now() time.Time {
	return time.Now().In(c.location)
}
630825
func NewScheduler(db *gorm.DB) *Scheduler {
	s := Scheduler{db: db}
	return &s
}
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
}
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
}
930865
func (e *UniversalExecutor) Exec(deadline time.Time, name string, args []string) ([]byte, int, error) {
	ctx, cancel := context.WithDeadline(context.Background(), deadline)
	defer cancel()
	return ExecScript(ctx, e.childCmd.Dir, e.commandCfg.Env, e.childCmd.SysProcAttr, name, args)
}
605675
func (r *Run) ScheduledForTime() (time.Time, error) {
	return time.Parse(time.RFC3339, r.ScheduledFor)
}
1086830
func listScheduledJobsCommand() *cli.Command {
	return &cli.Command{
		Name:     ListScheduledJobsCommandName,
		Usage:    ListScheduledJobsCommandUsage,
		Action:   ActionWrapper(listScheduledJobsAction),
		Category: "Jobs",
	}
}
871901
func (cron *Cron) Kill(job QorJobInterface) (err error) {
	cron.parseJobs()
	defer cron.writeCronJob()

	for _, cronJob := range cron.Jobs {
		if cronJob.JobID == job.GetJobID() {
			if process, err := os.FindProcess(cronJob.Pid); err == nil {
				if err = process.Kill(); err == nil {
					cronJob.Delete = true
					return nil
				}
			}
			return err
		}
	}
	return errors.New("failed to find job")
}
1070440
func CronLoader(b backend.B) caching.Loader {
	return func(c context.Context, k caching.Key, v *caching.Value) (*caching.Value, error) {
		return caching.CacheLoad(c, b, k, v)
	}
}
1364448
func (c *client) CronUpdate(owner, name, cron string, in *CronPatch) (*Cron, error) {
	out := new(Cron)
	uri := fmt.Sprintf(pathCron, c.addr, owner, name, cron)
	err := c.patch(uri, in, out)
	return out, err
}
4148
func (c *Cron) entrySnapshot() []*Entry {
	entries := []*Entry{}
	for _, e := range c.entries {
		entries = append(entries, &Entry{
			Schedule: e.Schedule,
			Next:     e.Next,
			Prev:     e.Prev,
			Job:      e.Job,
		})
	}
	return entries
}
577687
func NewScheduler() *Scheduler {
	return &Scheduler{
		Sink:             NewHTTPSink(),
		Timer:            timekeeper.RealTime{},
		ErrorHandler:     DefaultErrorHandler,
		ReportingDelayNs: DefaultReportingDelay.Nanoseconds(),
		callbackMap:      make(map[string]*callbackPair),
	}
}
887555
func Convert_v2alpha1_CronJob_To_batch_CronJob(in *v2alpha1.CronJob, out *batch.CronJob, s conversion.Scope) error {
	return autoConvert_v2alpha1_CronJob_To_batch_CronJob(in, out, s)
}
646102
func Convert_v1beta1_CronJobStatus_To_batch_CronJobStatus(in *v1beta1.CronJobStatus, out *batch.CronJobStatus, s conversion.Scope) error {
	return autoConvert_v1beta1_CronJobStatus_To_batch_CronJobStatus(in, out, s)
}
1040996
func NewSchedule(clock clock.Clock) *Schedule {
	return &Schedule{
		time: clock,
		m:    make(map[interface{}]*scheduleItem),
	}
}
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)
}