// Run sets the job to the schedule and returns the pointer to the job so it may be
// stopped or executed without waiting or an error.
973027
func (j *Job) Run(f func()) (*Job, error) {
	if j.err != nil {
		return nil, j.err
	}
	var next time.Duration
	var err error
	j.Quit = make(chan bool, 1)
	j.SkipWait = make(chan bool, 1)
	j.fn = f
	// Check for possible errors in scheduling
	next, err = j.schedule.nextRun()
	if err != nil {
		return nil, err
	}
	go func(j *Job) {
		for {
			select {
			case <-j.Quit:
				return
			case <-j.SkipWait:
				go runJob(j)
			case <-time.After(next):
				go runJob(j)
			}
			next, _ = j.schedule.nextRun()
		}
	}(j)
	return j, nil
}
703102
func (c *Cron) run() {
	// Figure out the next activation times for each entry.
	now := c.now()
	for _, entry := range c.entries {
		entry.Next = entry.Schedule.Next(now)
	}

	for {
		// Determine the next entry to run.
		sort.Sort(byTime(c.entries))

		var timer *time.Timer
		if len(c.entries) == 0 || c.entries[0].Next.IsZero() {
			// If there are no entries yet, just sleep - it still handles new entries
			// and stop requests.
			timer = time.NewTimer(100000 * time.Hour)
		} else {
			timer = time.NewTimer(c.entries[0].Next.Sub(now))
		}

		for {
			select {
			case now = <-timer.C:
				now = now.In(c.location)
				// Run every entry whose next time was less than now
				for _, e := range c.entries {
					if e.Next.After(now) || e.Next.IsZero() {
						break
					}
					go c.runWithRecovery(e.Job)
					e.Prev = e.Next
					e.Next = e.Schedule.Next(now)
				}

			case newEntry := <-c.add:
				timer.Stop()
				now = c.now()
				newEntry.Next = newEntry.Schedule.Next(now)
				c.entries = append(c.entries, newEntry)

			case <-c.snapshot:
				c.snapshot <- c.entrySnapshot()
				continue

			case <-c.stop:
				timer.Stop()
				return
			}

			break
		}
	}
}
835857
func (w *checkWatcher) Run(ctx context.Context) {
	defer close(w.done)

	// map of check IDs to their metadata
	checks := map[string]*checkRestart{}

	// timer for check polling
	checkTimer := time.NewTimer(0)
	defer checkTimer.Stop() // ensure timer is never leaked

	stopTimer := func() {
		checkTimer.Stop()
		select {
		case <-checkTimer.C:
		default:
		}
	}

	// disable by default
	stopTimer()

	// Main watch loop
	for {
		// disable polling if there are no checks
		if len(checks) == 0 {
			stopTimer()
		}

		select {
		case update := <-w.checkUpdateCh:
			if update.remove {
				// Remove a check
				delete(checks, update.checkID)
				continue
			}

			// Add/update a check
			checks[update.checkID] = update.checkRestart
			w.logger.Debug("watching check", "alloc_id", update.checkRestart.allocID,
				"task", update.checkRestart.taskName, "check", update.checkRestart.checkName)

			// if first check was added make sure polling is enabled
			if len(checks) == 1 {
				stopTimer()
				checkTimer.Reset(w.pollFreq)
			}

		case <-ctx.Done():
			return

		case <-checkTimer.C:
			checkTimer.Reset(w.pollFreq)

			// Set "now" as the point in time the following check results represent
			now := time.Now()

			results, err := w.consul.Checks()
			if err != nil {
				if !w.lastErr {
					w.lastErr = true
					w.logger.Error("failed retrieving health checks", "error", err)
				}
				continue
			}

			w.lastErr = false

			// Keep track of tasks restarted this period so they
			// are only restarted once and all of their checks are
			// removed.
			restartedTasks := map[string]struct{}{}

			// Loop over watched checks and update their status from results
			for cid, check := range checks {
				// Shortcircuit if told to exit
				if ctx.Err() != nil {
					return
				}

				if _, ok := restartedTasks[check.taskKey]; ok {
					// Check for this task already restarted; remove and skip check
					delete(checks, cid)
					continue
				}

				result, ok := results[cid]
				if !ok {
					// Only warn if outside grace period to avoid races with check registration
					if now.After(check.graceUntil) {
						w.logger.Warn("watched check not found in Consul", "check", check.checkName, "check_id", cid)
					}
					continue
				}

				restarted := check.apply(ctx, now, result.Status)
				if restarted {
					// Checks are registered+watched on
					// startup, so it's safe to remove them
					// whenever they're restarted
					delete(checks, cid)

					restartedTasks[check.taskKey] = struct{}{}
				}
			}

			// Ensure even passing checks for restartedTasks are removed
			if len(restartedTasks) > 0 {
				for cid, check := range checks {
					if _, ok := restartedTasks[check.taskKey]; ok {
						delete(checks, cid)
					}
				}
			}
		}
	}
}
198515
func Run(w io.Writer, appArgs []string, ask prompt.Prompt) (help.HelpMessage, error) {
	r := &runner{}
	return r.run(w, appArgs, ask)
}
148358
func (s *Simulated) Run(d time.Duration) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.init()

	end := s.now + AbsTime(d)
	for len(s.scheduled) > 0 {
		ev := s.scheduled[0]
		if ev.at > end {
			break
		}
		s.now = ev.at
		ev.do()
		s.scheduled = s.scheduled[1:]
	}
	s.now = end
}
52810
func (c *listCommand) Run(ctx *cmd.Context) error {
	api, err := c.NewActionAPIClient()
	if err != nil {
		return err
	}
	defer api.Close()

	actions, err := api.ApplicationCharmActions(params.Entity{Tag: c.applicationTag.String()})
	if err != nil {
		return err
	}

	if c.fullSchema {
		verboseSpecs := make(map[string]interface{})
		for k, v := range actions {
			verboseSpecs[k] = v.Params
		}

		if c.out.Name() == "default" {
			return c.out.WriteFormatter(ctx, cmd.FormatYaml, verboseSpecs)
		} else {
			return c.out.Write(ctx, verboseSpecs)
		}
	}

	shortOutput := make(map[string]string)
	var sortedNames []string
	for name, action := range actions {
		shortOutput[name] = action.Description
		if shortOutput[name] == "" {
			shortOutput[name] = "No description"
		}
		sortedNames = append(sortedNames, name)
	}
	naturalsort.Sort(sortedNames)

	var output interface{}
	switch c.out.Name() {
	case "yaml", "json":
		output = shortOutput
	default:
		if len(sortedNames) == 0 {
			ctx.Infof("No actions defined for %s.", c.applicationTag.Id())
			return nil
		}
		var list []listOutput
		for _, name := range sortedNames {
			list = append(list, listOutput{name, shortOutput[name]})
		}
		output = list
	}

	if c.out.Name() == "default" {
		return c.out.WriteFormatter(ctx, c.printTabular, output)
	} else {
		return c.out.Write(ctx, output)
	}

}
850892
func (c *Cron) run() {

	var effective time.Time
	now := time.Now().Local()

	// to figure next trig time for entries, referenced from now
	for _, e := range c.entries {
		e.Next = e.Schedule.Next(now)
	}

	for {
		sort.Sort(byTime(c.entries))
		if len(c.entries) > 0 {
			effective = c.entries[0].Next
		} else {
			effective = now.AddDate(15, 0, 0) // to prevent phantom jobs.
		}

		select {
		case now = <-after(effective.Sub(now)):
			// entries with same time gets run.
			for _, entry := range c.entries {
				if entry.Next != effective {
					break
				}
				entry.Prev = now
				entry.Next = entry.Schedule.Next(now)
				go entry.Job.Run()
			}
		case e := <-c.add:
			e.Next = e.Schedule.Next(time.Now())
			c.entries = append(c.entries, e)
		case <-c.stop:
			return // terminate go-routine.
		}
	}
}
843327
func (s *Simple) run() {
	for {
		select {
		case <-time.After(s.config.GCPeriodicity):
			s.GC()
		case <-s.halt:
			s.closeError <- nil
			// there is no cleanup required, so we just return
			return
		}
	}
}
1003584
func (c *DeploymentController) Run(workers int, stopCh <-chan struct{}) {
	defer utilruntime.HandleCrash()
	defer c.queue.ShutDown()

	klog.Infof("Starting deployer controller")

	// Wait for the dc store to sync before starting any work in this controller.
	if !cache.WaitForCacheSync(stopCh, c.rcListerSynced, c.podListerSynced) {
		return
	}

	klog.Infof("Deployer controller caches are synced. Starting workers.")

	for i := 0; i < workers; i++ {
		go wait.Until(c.worker, time.Second, stopCh)
	}

	<-stopCh

	klog.Infof("Shutting down deployer controller")
}
1318342
func (b *AdapterBase) Run(stopCh <-chan struct{}) error {
	server, err := b.Server()
	if err != nil {
		return err
	}

	return server.GenericAPIServer.PrepareRun().Run(stopCh)
}
400186
func (w Worker) Run() {
	w.Ready <- w

	for incoming := range w.DataChan {
		data := incoming.Data

		switch data[0] {
		case BundleTag[0]:
			bundle, err := ParseBundle(data, incoming.Sender)
			if err != nil {
				w.ErrChan <- err
			}
			if err := w.Dispatcher.Dispatch(bundle, w.ExactMatch); err != nil {
				w.ErrChan <- errors.Wrap(err, "dispatch bundle")
			}
		case MessageChar:
			msg, err := ParseMessage(data, incoming.Sender)
			if err != nil {
				w.ErrChan <- err
			}
			if err := w.Dispatcher.Invoke(msg, w.ExactMatch); err != nil {
				w.ErrChan <- errors.Wrap(err, "dispatch message")
			}
		default:
			w.ErrChan <- ErrParse
		}
		// Announce the worker is ready again.
		w.Ready <- w
	}
}
908958
func (w *Worker) Run() {

	// TODO: make this dynamic
	for i := 0; i < w.numGoroutines; i++ {
		log.Println("Starting handler routine ", i+1)
		go w.handlerLoop()
	}

	for {
		client, err := w.pool.Get()
		defer client.Close()
		if err != nil {
			log.Println("tasque: could not get client")
			select {
			case <-w.stopch:
				return
			case <-time.After(100 * time.Millisecond):
			}

		}

		for {
			select {
			case <-w.stopch:
				return
			default:
			}

			job, err := client.Get(getTimeout, w.channels...)

			if err == nil {

				if job.Data != nil {

					task := new(Task)
					if err := json.Unmarshal(job.Data, task); err != nil {
						log.Printf("tasque: Could not unmarshal message data: %s", err)
						continue
					}
					task.jobId = job.Id()

					select {
					case w.workchan <- task:
					case <-w.stopch:
						return
					}
				}

			} else {
				log.Printf("Error receiving: %s", err)
				client.Close()
				break
			}
		}
	}

}
521826
func (c *ProjectFinalizerController) Run(stopCh <-chan struct{}, workers int) {
	defer runtime.HandleCrash()
	defer c.queue.ShutDown()

	// Wait for the stores to fill
	if !cache.WaitForCacheSync(stopCh, c.cacheSynced) {
		return
	}

	klog.V(5).Infof("Starting workers")
	for i := 0; i < workers; i++ {
		go c.worker()
	}
	<-stopCh
	klog.V(1).Infof("Shutting down")
}
924079
func (sw *SleepWorkflow) Run(ctx context.Context, manager *Manager, wi *topo.WorkflowInfo) error {
	// Save all values, create a UI Node.
	sw.mu.Lock()
	sw.manager = manager
	sw.wi = wi

	sw.node.Listener = sw
	sw.node.Display = NodeDisplayDeterminate
	sw.node.Actions = []*Action{
		{
			Name:  pauseAction,
			State: ActionStateEnabled,
			Style: ActionStyleNormal,
		},
		{
			Name:  resumeAction,
			State: ActionStateDisabled,
			Style: ActionStyleNormal,
		},
	}
	sw.uiUpdateLocked()
	sw.node.BroadcastChanges(false /* updateChildren */)
	sw.mu.Unlock()

	for {
		sw.mu.Lock()
		data := *sw.data
		sw.mu.Unlock()

		if data.Slept == data.Duration {
			break
		}

		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-time.After(time.Second):
			if !data.Paused {
				sw.mu.Lock()
				sw.data.Slept++
				// UI update every second.
				sw.uiUpdateLocked()
				sw.node.BroadcastChanges(false /* updateChildren */)
				// Checkpoint every 5 seconds.
				if sw.data.Slept%5 == 0 {
					if err := sw.checkpointLocked(ctx); err != nil {
						sw.mu.Unlock()
						return err
					}
				}
				sw.mu.Unlock()
			}
		}
	}

	return nil
}
421616
func (*ExecRunner) Run(cmd string) error {
	glog.Infoln("Run:", cmd)
	c := exec.Command("/bin/bash", "-c", cmd)
	if err := c.Run(); err != nil {
		return errors.Wrapf(err, "running command: %s", cmd)
	}
	return nil
}
1320246
func (c *runner) Run(name string, arg ...string) error {
	return c.RunWithOptions(CommandOpts{}, name, arg...)
}
875830
func (s *AttachedScheduler) Run(ctx context.Context, app *twelvefactor.Manifest) error {
	if len(app.Processes) != 1 {
		return fmt.Errorf("docker: cannot run mutliple processes with attached scheduler")
	}

	p := app.Processes[0]
	// Attached means stdout, stdin is attached.
	attached := p.Stdin != nil || p.Stdout != nil || p.Stderr != nil

	if attached {
		return s.dockerScheduler.Run(ctx, app)
	} else {
		return s.Scheduler.Run(ctx, app)
	}
}