// AppBeginBackgroundTask notifies us that an app background task has been started on our behalf. This
// function will return once we no longer need any time in the background.
554022
func AppBeginBackgroundTask(pusher PushNotifier) {
	if !isInited() {
		return
	}
	defer kbCtx.Trace("AppBeginBackgroundTask", func() error { return nil })()
	ctx := context.Background()
	// Poll active deliveries in case we can shutdown early
	beginTime := libkb.ForceWallClock(time.Now())
	ticker := time.NewTicker(5 * time.Second)
	appState := kbCtx.MobileAppState.State()
	if appState != keybase1.MobileAppState_BACKGROUNDACTIVE {
		kbCtx.Log.Debug("AppBeginBackgroundTask: not in background mode, early out")
		return
	}
	var g *errgroup.Group
	g, ctx = errgroup.WithContext(ctx)
	g.Go(func() error {
		select {
		case appState = <-kbCtx.MobileAppState.NextUpdate(&appState):
			kbCtx.Log.Debug(
				"AppBeginBackgroundTask: app state change, aborting with no task shutdown: %v", appState)
			return errors.New("app state change")
		case <-ctx.Done():
			return ctx.Err()
		}
	})
	g.Go(func() error {
		ch, cancel := kbChatCtx.MessageDeliverer.NextFailure()
		defer cancel()
		select {
		case obrs := <-ch:
			kbCtx.Log.Debug(
				"AppBeginBackgroundTask: failure received, alerting the user: %d marked", len(obrs))
			pushPendingMessageFailure(obrs, pusher)
			return errors.New("failure received")
		case <-ctx.Done():
			return ctx.Err()
		}
	})
	g.Go(func() error {
		successCount := 0
		for {
			select {
			case <-ticker.C:
				obrs, err := kbChatCtx.MessageDeliverer.ActiveDeliveries(ctx)
				if err != nil {
					kbCtx.Log.Debug("AppBeginBackgroundTask: failed to query active deliveries: %s", err)
					continue
				}
				if len(obrs) == 0 {
					kbCtx.Log.Debug("AppBeginBackgroundTask: delivered everything: successCount: %d",
						successCount)
					// We can race the failure case here, so lets go a couple passes of no pending
					// convs before we abort due to ths condition.
					if successCount > 1 {
						return errors.New("delivered everything")
					}
					successCount++
				}
				curTime := libkb.ForceWallClock(time.Now())
				if curTime.Sub(beginTime) >= 10*time.Minute {
					kbCtx.Log.Debug("AppBeginBackgroundTask: failed to deliver and time is up, aborting")
					pushPendingMessageFailure(obrs, pusher)
					return errors.New("time expired")
				}
			case <-ctx.Done():
				return ctx.Err()
			}
		}
	})
	if err := g.Wait(); err != nil {
		kbCtx.Log.Debug("AppBeginBackgroundTask: dropped out of wait because: %s", err)
	}
}
496233
func SetBackground(c color.Color) {
	if !engo.Headless() {
		r, g, b, a := c.RGBA()

		engo.Gl.ClearColor(float32(r)/0xffff, float32(g)/0xffff, float32(b)/0xffff, float32(a)/0xffff)
	}
}
52105
func (m TaskManager) LaunchTask(c context.Context, ctl task.Controller) error {
	cfg := ctl.Task().(*messages.GitilesTask)
	ctl.DebugLog("Repo: %s, Refs: %s", cfg.Repo, cfg.Refs)

	g, err := m.getGitilesClient(c, ctl, cfg)
	if err != nil {
		return err
	}
	refs, err := m.fetchRefsState(c, ctl, cfg, g)
	if err != nil {
		ctl.DebugLog("Error fetching state of the world: %s", err)
		return err
	}

	refs.pruneKnown(ctl)
	leftToProcess, err := m.emitTriggersRefAtATime(c, ctl, g, cfg, refs)

	if err != nil {
		switch {
		case leftToProcess == 0:
			panic(err) // leftToProcess must include the one processing of which failed.
		case refs.changed > 0:
			// Even though we hit error, we had progress. So, ignore error as transient.
			ctl.DebugLog("ignoring error %s as transient", err)
		default:
			ctl.DebugLog("no progress made due to %s", err)
			return err
		}
	}

	switch {
	case leftToProcess > 0 && refs.changed == 0:
		panic(errors.New("no progress with no errors must not happen"))
	case refs.changed == 0:
		ctl.DebugLog("No changes detected")
		ctl.State().Status = task.StatusSucceeded
		return nil
	case leftToProcess > 0:
		ctl.DebugLog("%d changed refs processed, %d refs not yet examined", refs.changed, leftToProcess)
	default:
		ctl.DebugLog("All %d changed refs processed", refs.changed)
	}
	// Force save to ensure triggers are actually emitted.
	if err := ctl.Save(c); err != nil {
		// At this point, triggers have not been sent, so bail now and don't save
		// the refs' heads newest values.
		return err
	}
	if err := saveState(c, ctl.JobID(), cfg.Repo, refs.known); err != nil {
		return err
	}
	ctl.DebugLog("Saved %d known refs", len(refs.known))
	ctl.State().Status = task.StatusSucceeded
	return nil
}
366792
func (r *Application) AllTaskRunning() bool {
	if r.Instances == nil || *r.Instances == 0 {
		return true
	}
	if r.Tasks == nil {
		return false
	}
	if r.TasksRunning == *r.Instances {
		return true
	}
	return false
}
281840
func (j *tlfJournal) doBackgroundWork(ctx context.Context) <-chan error {
	errCh := make(chan error, 1)
	// TODO: Handle panics.
	go func() {
		defer j.wg.Done()
		errCh <- j.flush(ctx)
		close(errCh)
	}()
	return errCh
}
1165542
func (i *FuncInterceptor) BeforeTask(decision *swf.PollForDecisionTaskOutput) {
	if i.BeforeTaskFn != nil {
		i.BeforeTaskFn(decision)
	}
}
771891
func NewPerUserKeyUpgradeBackground(g *libkb.GlobalContext, args *PerUserKeyUpgradeBackgroundArgs) *PerUserKeyUpgradeBackground {
	task := NewBackgroundTask(g, &BackgroundTaskArgs{
		Name:     "PerUserKeyUpgradeBackground",
		F:        PerUserKeyUpgradeBackgroundRound,
		Settings: PerUserKeyUpgradeBackgroundSettings,

		testingMetaCh:     args.testingMetaCh,
		testingRoundResCh: args.testingRoundResCh,
	})
	return &PerUserKeyUpgradeBackground{
		Contextified: libkb.NewContextified(g),
		args:         args,
		// Install the task early so that Shutdown can be called before RunEngine.
		task: task,
	}
}
897846
func (client *Client) GetApplicationTasks(appGUID string, query ...Query) ([]Task, Warnings, error) {
	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.GetApplicationTasksRequest,
		URIParams: internal.Params{
			"app_guid": appGUID,
		},
		Query: query,
	})
	if err != nil {
		return nil, nil, err
	}

	var fullTasksList []Task
	warnings, err := client.paginate(request, Task{}, func(item interface{}) error {
		if task, ok := item.(Task); ok {
			fullTasksList = append(fullTasksList, task)
		} else {
			return ccerror.UnknownObjectInListError{
				Expected:   Task{},
				Unexpected: item,
			}
		}
		return nil
	})

	return fullTasksList, warnings, err
}
791387
func (c *ECS) WaitUntilTasksRunning(input *DescribeTasksInput) error {
	return c.WaitUntilTasksRunningWithContext(aws.BackgroundContext(), input)
}
1181734
func (self *FSock) doBackgroudJob(event string) { // add mutex protection
	evMap := EventToMap(event)
	jobUuid, has := evMap["Job-UUID"]
	if !has {
		self.logger.Err("<FSock> BACKGROUND_JOB with no Job-UUID")
		return
	}

	var out chan string
	self.fsMutex.RLock()
	out, has = self.backgroundChans[jobUuid]
	self.fsMutex.RUnlock()
	if !has {
		self.logger.Err(fmt.Sprintf("<FSock> BACKGROUND_JOB with UUID %s lost!", jobUuid))
		return // not a requested bgapi
	}

	self.fsMutex.Lock()
	delete(self.backgroundChans, jobUuid)
	self.fsMutex.Unlock()

	out <- evMap[EventBodyTag]
}
53481
func (server *Server) SendTask(signature *tasks.Signature) (*result.AsyncResult, error) {
	return server.SendTaskWithContext(context.Background(), signature)
}
1109878
func (g *TaskGroup) AddTask(t *Task) *TaskGroup {
	g.Tasks = append(g.Tasks, t)
	return g
}
1296346
func TaskTrack(ctx types.Context) *types.Task {
	return getTaskService(ctx).TaskTrack(ctx)
}
378661
func (ow *outerWorker) buildTask(ctx context.Context) (*lookUpJoinTask, error) {
	ow.executor.newFirstChunk()

	task := &lookUpJoinTask{
		doneCh:            make(chan error, 1),
		outerResult:       ow.executor.newFirstChunk(),
		encodedLookUpKeys: chunk.NewChunkWithCapacity([]*types.FieldType{types.NewFieldType(mysql.TypeBlob)}, ow.ctx.GetSessionVars().MaxChunkSize),
		lookupMap:         mvmap.NewMVMap(),
	}
	task.memTracker = memory.NewTracker(stringutil.MemoizeStr(func() string { return fmt.Sprintf("lookup join task %p", task) }), -1)
	task.memTracker.AttachTo(ow.parentMemTracker)

	ow.increaseBatchSize()
	if ow.lookup.isOuterJoin { // if is outerJoin, push the requiredRows down
		requiredRows := int(atomic.LoadInt64(&ow.lookup.requiredRows))
		task.outerResult.SetRequiredRows(requiredRows, ow.maxBatchSize)
	} else {
		task.outerResult.SetRequiredRows(ow.batchSize, ow.maxBatchSize)
	}

	task.memTracker.Consume(task.outerResult.MemoryUsage())
	for !task.outerResult.IsFull() {
		err := ow.executor.Next(ctx, chunk.NewRecordBatch(ow.executorChk))
		if err != nil {
			return task, err
		}
		if ow.executorChk.NumRows() == 0 {
			break
		}

		oldMemUsage := task.outerResult.MemoryUsage()
		task.outerResult.Append(ow.executorChk, 0, ow.executorChk.NumRows())
		newMemUsage := task.outerResult.MemoryUsage()
		task.memTracker.Consume(newMemUsage - oldMemUsage)
	}
	if task.outerResult.NumRows() == 0 {
		return nil, nil
	}

	if ow.filter != nil {
		outerMatch := make([]bool, 0, task.outerResult.NumRows())
		var err error
		task.outerMatch, err = expression.VectorizedFilter(ow.ctx, ow.filter, chunk.NewIterator4Chunk(task.outerResult), outerMatch)
		if err != nil {
			return task, err
		}
		task.memTracker.Consume(int64(cap(task.outerMatch)))
	}
	return task, nil
}
1287142
func (i *FuncInterceptor) AfterTaskComplete(activity *swf.PollForActivityTaskOutput, result interface{}) {
	if i.AfterTaskCompleteFn != nil {
		i.AfterTaskCompleteFn(activity, result)
	}
}
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))
		})
	})
}
1007528
func (s *BurninDestinationSettings) SetBackgroundColor(v string) *BurninDestinationSettings {
	s.BackgroundColor = &v
	return s
}