////////////////////////////////////////////////////////////////////////////////
// Cron handling.
// execCronTickTask corresponds to a delayed tick emitted by a cron state
// machine.
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))
		})
	})
}
188776
function (data) {
  var q = _q.defer();
  data = data.replace(/\'/g,"\\\'");
  data = data.replace(/\"/g,'\\\"');
  exec(`echo "${data}" | crontab -`, (err, stdout, stderr) => {
    if (err) q.reject(err);
    if(stdout)q.resolve(stdout);
    else q.resolve(stderr);
  });
  return q.promise;
}
276076
func (m TaskManager) LaunchTask(c context.Context, ctl task.Controller) error {
	cfg := ctl.Task().(*messages.UrlFetchTask)
	started := clock.Now(c)

	// Defaults.
	method := cfg.Method
	if method == "" {
		method = "GET"
	}
	timeout := cfg.TimeoutSec
	if timeout == 0 {
		timeout = 60
	}

	ctl.DebugLog("%s %s", method, cfg.Url)

	// There must be no errors here in reality, since cfg is validated already by
	// ValidateProtoMessage.
	u, err := url.Parse(cfg.Url)
	if err != nil {
		return err
	}

	type tuple struct {
		resp *http.Response
		body []byte // first 4Kb of the response, for debug log
		err  error
	}
	result := make(chan tuple)

	// Do the fetch asynchronously with datastore update.
	go func() {
		defer close(result)
		c, _ := clock.WithTimeout(c, time.Duration(timeout)*time.Second)
		client := &http.Client{Transport: urlfetch.Get(c)}
		resp, err := client.Do(&http.Request{
			Method: method,
			URL:    u,
		})
		if err != nil {
			result <- tuple{nil, nil, err}
			return
		}
		defer resp.Body.Close()
		// Ignore read errors here. HTTP status code is set, it's the main output
		// of the operation. Read 4K only since we use body only for debug message
		// that is limited in size.
		buf := bytes.Buffer{}
		io.CopyN(&buf, resp.Body, 4096)
		result <- tuple{resp, buf.Bytes(), nil}
	}()

	// Save the invocation log now (since URL fetch can take up to 8 minutes).
	// Ignore errors. As long as final Save is OK, we don't care about this one.
	// Do NOT set status to StatusRunning, because by doing so we take
	// responsibility to detect crashes below and we don't want to do it (let
	// the scheduler retry LaunchTask automatically instead).
	if err := ctl.Save(c); err != nil {
		logging.Warningf(c, "Failed to save invocation state: %s", err)
	}

	// Wait for completion.
	res := <-result

	duration := clock.Now(c).Sub(started)
	status := task.StatusSucceeded
	if res.err != nil || res.resp.StatusCode >= 400 {
		status = task.StatusFailed
	}

	ctl.DebugLog("Finished with overall status %s in %s", status, duration)
	if res.err != nil {
		ctl.DebugLog("URL fetch error: %s", res.err)
	} else {
		ctl.DebugLog(dumpResponse(res.resp, res.body))
	}
	ctl.State().Status = status
	return nil
}
1302131
public void schedule(TimerTask task, boolean checkIfAlreadyPresent) {
		
		final TimerTaskData taskData = task.getData(); 
		final Serializable taskID = taskData.getTaskID();
		task.setScheduler(this);
		
		if (logger.isDebugEnabled()) {
			logger.debug("Scheduling task with id " + taskID);
		}
		
		// store the task and data
		final TimerTaskCacheData timerTaskCacheData = new TimerTaskCacheData(taskID, baseFqn, cluster);
		if (timerTaskCacheData.create()) {
			timerTaskCacheData.setTaskData(taskData);
		} else if(checkIfAlreadyPresent) {
            throw new IllegalStateException("timer task " + taskID + " already scheduled");
		}
				
		// schedule task
		final SetTimerAfterTxCommitRunnable setTimerAction = new SetTimerAfterTxCommitRunnable(task, this);
		if (txManager != null) {
			try {
				Transaction tx = txManager.getTransaction();
				if (tx != null) {
					TransactionContext txContext = TransactionContextThreadLocal.getTransactionContext();
					if (txContext == null) {
						txContext = new TransactionContext();
						tx.registerSynchronization(new TransactionSynchronization(txContext));
					}
					txContext.put(taskID, setTimerAction);					
					task.setSetTimerTransactionalAction(setTimerAction);
				}
				else {
					setTimerAction.run();
				}
			}
			catch (Throwable e) {
				remove(taskID,true);
				throw new RuntimeException("Unable to register tx synchronization object",e);
			}
		}
		else {
			setTimerAction.run();
		}		
	}
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)
}
64868
function isTaskReady(task) {
  var after       = task.after || new Date().getTime();
  var delay       = task.delay || 0;

  return task.status === 'ready' &&
  ((after + delay) <= new Date().getTime()) &&
  !TaskLock.isTaskLocked(task);
}
987032
func pollTaskAndWait(task enamlbosh.BoshTask, client *enamlbosh.Client, tries int) error {
	UIPrint("polling task...")
	defer UIPrint(fmt.Sprintf("Finished with Task %s", task.Description))
	ticker := time.Tick(time.Second)
	count := 0
	for {
		<-ticker
		var err error
		task, err = client.GetTask(task.ID)
		if err != nil {
			return err
		}
		switch task.State {
		case enamlbosh.StatusDone:
			UIPrintStatus(fmt.Sprintf("task state %s", task.State))
			return nil
		case enamlbosh.StatusCancelled, enamlbosh.StatusError:
			err := fmt.Errorf("%s - %s", task.State, task.Description)
			lo.G.Error("task error: " + err.Error())
			return err
		default:
			UIPrintStatus(fmt.Sprintf("task '%s' is %s", task.Description, task.State))
		}
		count++

		if tries != -1 && count >= tries {
			UIPrintStatus("hit poll limit, exiting task poller without error")
			return nil
		}
	}
}
985101
func (e *engineImpl) execEnqueueTriggersTask(c context.Context, tqTask proto.Message) error {
	msg := tqTask.(*internal.EnqueueTriggersTask)

	c = logging.SetField(c, "JobID", msg.JobId)

	logTriggers := func() {
		for _, t := range msg.Triggers {
			logging.Infof(c, "  %s (emitted by %q, inv %d)", t.Id, t.JobId, t.InvocationId)
		}
	}

	// Don't even bother if the job is paused or disabled. Note that if the job
	// became inactive after this check, the triage will get rid of pending
	// triggers itself. Thus the check here is just an optimization.
	job, err := e.getJob(c, msg.JobId)
	if err != nil {
		logging.WithError(err).Errorf(c, "Failed to grab Job entity")
		return err // transient error getting the job
	}
	if job == nil || !job.Enabled || job.Paused {
		logging.Warningf(c, "Discarding the following triggers since the job is inactive")
		logTriggers()
		return nil
	}

	logging.Infof(c, "Adding the following triggers to the pending triggers set")
	logTriggers()
	if err := pendingTriggersSet(c, msg.JobId).Add(c, msg.Triggers); err != nil {
		logging.WithError(err).Errorf(c, "Failed to update pending triggers set")
		return err
	}

	return e.kickTriageNow(c, msg.JobId)
}
1284441
function CruxTaskEntry(name) {
  this.autorun = true;  // we can disable auto running.
  this.name = name;
  this.debug = false;
  this.type = 'serial'; // the type of this task. Can be: serial or parallel
  this.__queue = [];
  this.__actions = {};
  this.__hasActions = false;
  this.__started = false;
  this.__scheduled = false;
  this.__wait = 0;
  this.__running = false;
  this.__handlers = {}; // currently, only "failed", "timeout" and "completed"
  this.__options = {
    delay: 10, // number of seconds to delay the run.
    timeout: 0,  // number of seconds until we consider the task failed.
    timer: 0    // number of seconds between calls. Defaults to 0(cyclic disabled)
  };
  this.__run_queue = [];  // we place any run requests while running here.
  EventEmitter.call(this);
}
738324
func (e *engineImpl) execKickTriageTask(c context.Context, tqTask proto.Message) error {
	return e.kickTriageNow(c, tqTask.(*internal.KickTriageTask).JobId)
}
867678
async function delayIfNeeded() {
  if (gT.engineConsts.extJsClickDelay) {
    await gT.s.driver.sleep(gT.engineConsts.extJsClickDelay, false);
  }
}
797899
func (tr *TaskReaper) tick() {
	// this signals that a tick has occurred. it exists solely for testing.
	if tr.tickSignal != nil {
		// try writing to this channel, but if it's full, fall straight through
		// and ignore it.
		select {
		case tr.tickSignal <- struct{}{}:
		default:
		}
	}

	if len(tr.dirty) == 0 && len(tr.cleanup) == 0 {
		return
	}

	defer func() {
		tr.cleanup = nil
	}()

	deleteTasks := make(map[string]struct{})
	for _, tID := range tr.cleanup {
		deleteTasks[tID] = struct{}{}
	}

	// Check history of dirty tasks for cleanup.
	// Note: Clean out the dirty set at the end of this tick iteration
	// in all but one scenarios (documented below).
	// When tick() finishes, the tasks in the slot were either cleaned up,
	// or it was skipped because it didn't meet the criteria for cleaning.
	// Either way, we can discard the dirty set because future events on
	// that slot will cause the task to be readded to the dirty set
	// at that point.
	//
	// The only case when we keep the slot dirty is when there are more
	// than one running tasks present for a given slot.
	// In that case, we need to keep the slot dirty to allow it to be
	// cleaned when tick() is called next and one or more the tasks
	// in that slot have stopped running.
	tr.store.View(func(tx store.ReadTx) {
		for dirty := range tr.dirty {
			service := store.GetService(tx, dirty.ServiceID)
			if service == nil {
				delete(tr.dirty, dirty)
				continue
			}

			taskHistory := tr.taskHistory

			// If MaxAttempts is set, keep at least one more than
			// that number of tasks (this overrides TaskHistoryRetentionLimit).
			// This is necessary to reconstruct restart history when the orchestrator starts up.
			// TODO(aaronl): Consider hiding tasks beyond the normal
			// retention limit in the UI.
			// TODO(aaronl): There are some ways to cut down the
			// number of retained tasks at the cost of more
			// complexity:
			//   - Don't force retention of tasks with an older spec
			//     version.
			//   - Don't force retention of tasks outside of the
			//     time window configured for restart lookback.
			if service.Spec.Task.Restart != nil && service.Spec.Task.Restart.MaxAttempts > 0 {
				taskHistory = int64(service.Spec.Task.Restart.MaxAttempts) + 1
			}

			// Negative value for TaskHistoryRetentionLimit is an indication to never clean up task history.
			if taskHistory < 0 {
				delete(tr.dirty, dirty)
				continue
			}

			var historicTasks []*api.Task

			switch service.Spec.GetMode().(type) {
			case *api.ServiceSpec_Replicated:
				// Clean out the slot for which we received EventCreateTask.
				var err error
				historicTasks, err = store.FindTasks(tx, store.BySlot(dirty.ServiceID, dirty.Slot))
				if err != nil {
					continue
				}

			case *api.ServiceSpec_Global:
				// Clean out the node history in case of global services.
				tasksByNode, err := store.FindTasks(tx, store.ByNodeID(dirty.NodeID))
				if err != nil {
					continue
				}

				for _, t := range tasksByNode {
					if t.ServiceID == dirty.ServiceID {
						historicTasks = append(historicTasks, t)
					}
				}
			}

			if int64(len(historicTasks)) <= taskHistory {
				delete(tr.dirty, dirty)
				continue
			}

			// TODO(aaronl): This could filter for non-running tasks and use quickselect
			// instead of sorting the whole slice.
			// TODO(aaronl): This sort should really use lamport time instead of wall
			// clock time. We should store a Version in the Status field.
			sort.Sort(orchestrator.TasksByTimestamp(historicTasks))

			runningTasks := 0
			for _, t := range historicTasks {
				// Historical tasks can be considered for cleanup if:
				// 1. The task has reached a terminal state i.e. actual state beyond TaskStateRunning.
				// 2. The task has not yet become running and desired state is a terminal state i.e.
				// actual state not yet TaskStateAssigned and desired state beyond TaskStateRunning.
				if taskInTerminalState(t) || taskWillNeverRun(t) {
					deleteTasks[t.ID] = struct{}{}

					taskHistory++
					if int64(len(historicTasks)) <= taskHistory {
						break
					}
				} else {
					// all other tasks are counted as running.
					runningTasks++
				}
			}

			// The only case when we keep the slot dirty at the end of tick()
			// is when there are more than one running tasks present
			// for a given slot.
			// In that case, we keep the slot dirty to allow it to be
			// cleaned when tick() is called next and one or more of
			// the tasks in that slot have stopped running.
			if runningTasks <= 1 {
				delete(tr.dirty, dirty)
			}
		}
	})

	// Perform cleanup.
	if len(deleteTasks) > 0 {
		tr.store.Batch(func(batch *store.Batch) error {
			for taskID := range deleteTasks {
				batch.Update(func(tx store.Tx) error {
					return store.DeleteTask(tx, taskID)
				})
			}
			return nil
		})
	}
}
429300
function _tick() {
    var config = this._config;
    var now = Date.now();
    var dt = now - this._before;

    if (!this._started) {
      // The ticker has been stopped
      return;
    }

    if (config.async) {
      config.task(this._tock, dt);
    } else {
      config.task(dt);
      this._tock();
    }
  }
1010662
function next(i, p, task) {
        let iResult = task ? { value: task, done: false } : i.next();
        try {
            if (iResult.done) {
                publish($state);
                return;
            }
            const result = iResult.value($state, p);
            /* Promise(Like) */
            if (result && typeof result.then === 'function') {
                result.then(resolved, rejected);
                publish($state);
                return;
                function resolved(t) {
                    const _t = (typeof t === 'function') && t;
                    next(i, p, _t);
                }
                ;
                function rejected(err) {
                    publish($state, err);
                }
            }
            if (!iResult.done) {
                result && setState(result);
                next(i, p);
                return;
            }
        }
        catch (e) {
            publish($state, e);
        }
    }
1250825
public static <TResult> Task<TResult> call(final Callable<TResult> callable, Executor executor,
      final CancellationToken ct) {
    final bolts.TaskCompletionSource<TResult> tcs = new bolts.TaskCompletionSource<>();
    try {
      executor.execute(new Runnable() {
        @Override
        public void run() {
          if (ct != null && ct.isCancellationRequested()) {
            tcs.setCancelled();
            return;
          }

          try {
            tcs.setResult(callable.call());
          } catch (CancellationException e) {
            tcs.setCancelled();
          } catch (Exception e) {
            tcs.setError(e);
          }
        }
      });
    } catch (Exception e) {
      tcs.setError(new ExecutorException(e));
    }

    return tcs.getTask();
  }
1162270
static <T> ContinuableFuture<T> executeOnUiThread(final Callable<T> action, final long delay) {
        return execute(new FutureTask<>(action), _UI_EXECUTOR, delay);
    }
850184
private void scheduleSendTask(boolean runNow) {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {

                byte[] packet;

                try {
                    packet = packets.get(0);

                } catch (IndexOutOfBoundsException e) {
                    // No packets left; return without scheduling another run
                    return;

                }

                charc.setValue(packet);
                boolean result = gattClient.writeCharacteristic(charc);

                if (result) {
                    packets.remove(0);
                    int id = ids.remove(0);
                    retries = 0;

                    if (onPacketSent != null) {
                        onPacketSent.onResult(id);
                    }
                    Log.d(TAG, "Packet " + id + " sent after " + retries + " retries");

                } else {
                    retries++;

                }

                scheduleSendTask(false);
            }
        };

        if (runNow) {
            task.run();

        } else {
            sendTimer.schedule(task, SEND_INTERVAL);

        }
    }