// DeleteScheduledTask delete schedule task
//
// You can read doc at https://help.aliyun.com/document_detail/25960.html?spm=5176.doc25959.6.641.aGdNuW
540894
func (client *Client) DeleteScheduledTask(args *DeleteScheduledTaskArgs) (resp *DeleteScheduledTaskResponse, err error) {
	response := DeleteScheduledTaskResponse{}
	err = client.Invoke("DeleteScheduledTask", args, &response)

	if err != nil {
		return nil, err
	}
	return &response, nil
}
1230875
func (*CallingGoroutineDispatcher) DispatchTask(task *swf.PollForActivityTaskOutput, handler func(*swf.PollForActivityTaskOutput)) {
	handler(task)
}
713671
func NewScheduler() (*Scheduler, error) {
	defaultClusterOperations := map[string]bool{
		"HorizontalReshardingTask": true,
		"VerticalSplitTask":        true,
	}

	s := &Scheduler{
		registeredClusterOperations:    defaultClusterOperations,
		idGenerator:                    IDGenerator{},
		toBeScheduledClusterOperations: make(chan ClusterOperationInstance, 10),
		state:                          stateNotRunning,
		taskCreator:                    defaultTaskCreator,
		pendingOpsWg:                   &sync.WaitGroup{},
		activeClusterOperations:        make(map[string]ClusterOperationInstance),
		finishedClusterOperations:      make(map[string]ClusterOperationInstance),
	}

	return s, nil
}
1230809
func (m *TaskManager) Delete(ctx context.Context, id string) {
	m.tasks.Delete(ctx, id)
}
88756
func (client *Client) ModifyScheduledTask(args *ModifyScheduledTaskArgs) (resp *ModifyScheduledTaskResponse, err error) {
	response := ModifyScheduledTaskResponse{}
	err = client.Invoke("ModifyScheduledTask", args, &response)

	if err != nil {
		return nil, err
	}
	return &response, nil
}
893364
func NewDeleteTask(ctx *middleware.Context, handler DeleteTaskHandler) *DeleteTask {
	return &DeleteTask{Context: ctx, Handler: handler}
}
1192905
func (r *Runtime) Delete(ctx context.Context, id string) {
	r.tasks.Delete(ctx, id)
}
337874
func (c *Client) RemoveTask(id string) *RemoveTasksResult {
	resp, err := c.do("DELETE", fmt.Sprintf("/tasks/%v", id), ContentTypeJSON)
	if err != nil {
		return &RemoveTasksResult{Err: err}
	}

	switch resp.Meta.Type {
	case rbody.ScheduledTaskRemovedType:
		// Success
		return &RemoveTasksResult{resp.Body.(*rbody.ScheduledTaskRemoved), nil}
	case rbody.ErrorType:
		return &RemoveTasksResult{Err: resp.Body.(*rbody.Error)}
	default:
		return &RemoveTasksResult{Err: ErrAPIResponseMetaType}
	}
}
1268600
func (g *GoroutinePool) Schedule(job, onCanceled func()) {
	g.wg.Add(1)
	// Note: We could save a bit of memory by preallocating maxConcurrentJobs
	// goroutines instead of one goroutine per item.
	go func() {
		defer g.wg.Done()
		if g.sema.wait(g.ctx) == nil {
			defer g.sema.signal()
			job()
		} else if onCanceled != nil {
			onCanceled()
		}
	}()
}
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))
		})
	})
}
1172550
func (s *scheduler) GetTask(id string) (core.Task, error) {
	t, err := s.getTask(id)
	if err != nil {
		schedulerLogger.WithFields(log.Fields{
			"_block":  "get-task",
			"_error":  ErrTaskNotFound,
			"task-id": id,
		}).Error("error getting task")
		return nil, err // We do this to send back an explicit nil on the interface
	}
	return t, nil
}
233446
func (e *engineImpl) execScheduleTimersTask(c context.Context, tqTask proto.Message) error {
	msg := tqTask.(*internal.ScheduleTimersTask)

	tasks := make([]*tq.Task, len(msg.Timers))
	for i, timer := range msg.Timers {
		tasks[i] = &tq.Task{
			ETA: google.TimeFromProto(timer.Eta),
			Payload: &internal.TimerTask{
				JobId: msg.JobId,
				InvId: msg.InvId,
				Timer: timer,
			},
		}
	}

	return e.cfg.Dispatcher.AddTask(c, tasks...)
}
1245949
func (c *Client) TerminateTask(guid string) error {
	req := c.NewRequest("PUT", fmt.Sprintf("/v3/tasks/%s/cancel", guid))
	resp, err := c.DoRequest(req)
	if err != nil {
		return errors.Wrap(err, "Error terminating task")
	}
	defer resp.Body.Close()

	if resp.StatusCode != 202 {
		return errors.Wrapf(err, "Failed terminating task, response status code %d", resp.StatusCode)
	}
	return nil
}
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
}
1069153
func (c *Core) scheduleUpgradeCleanup(ctx context.Context) error {
	// List the upgrades
	upgrades, err := c.barrier.List(ctx, keyringUpgradePrefix)
	if err != nil {
		return errwrap.Wrapf("failed to list upgrades: {{err}}", err)
	}

	// Nothing to do if no upgrades
	if len(upgrades) == 0 {
		return nil
	}

	// Schedule cleanup for all of them
	time.AfterFunc(keyRotateGracePeriod, func() {
		sealed, err := c.barrier.Sealed()
		if err != nil {
			c.logger.Warn("failed to check barrier status at upgrade cleanup time")
			return
		}
		if sealed {
			c.logger.Warn("barrier sealed at upgrade cleanup time")
			return
		}
		for _, upgrade := range upgrades {
			path := fmt.Sprintf("%s%s", keyringUpgradePrefix, upgrade)
			if err := c.barrier.Delete(ctx, path); err != nil {
				c.logger.Error("failed to cleanup upgrade", "path", path, "error", err)
			}
		}
	})
	return nil
}
956553
func (sm *schedulerMetrics) ReleaseTask(tid string) {
	sm.claimsActive.Dec()
	sm.runsActive.DeleteLabelValues(tid)
	sm.runsComplete.DeleteLabelValues(tid, statusString(true))
	sm.runsComplete.DeleteLabelValues(tid, statusString(false))
}
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)
}