HTTP endpoint for canceling tasks

  If an active task is cancelled, an inactive task with the same code and the
  smallest interval will be activated if it exists.
976391
def cancel():
  
  task_id = request.form['id']
  task = Task.query.get(task_id)

  if not task:
    return json.dumps({
      'status': 'success',
      'id': None,
    })

  task.delete()

  if task.active:
    current_app.scheduler.cancel(task_id)

    code = task.code
    other_task = Task.query.filter_by(code=code).order_by('interval').first()
    if other_task:
      other_task.active = True
      other_task.save()
      current_app.scheduler.schedule({
        'id': other_task.id,
        'code': other_task.code,
        'interval': other_task.interval
      })

  return json.dumps({
    'status': 'success',
    'id': task_id,
  })
1271580
def stop_task(self, task_name):
        '''
        
        '''
        for greenlet in self.active[task_name]:
            try:
                # Do not need to check if greenlet is dead, gevent does it already
                gevent.kill(greenlet)
                self.active[task_name] = []
            except BaseException:
                pass
112046
def _check_request(self):
        ''''''
        # check _postpone_request first
        todo = []
        for task in self._postpone_request:
            if task['project'] not in self.projects:
                continue
            if self.projects[task['project']].task_queue.is_processing(task['taskid']):
                todo.append(task)
            else:
                self.on_request(task)
        self._postpone_request = todo

        tasks = {}
        while len(tasks) < self.LOOP_LIMIT:
            try:
                task = self.newtask_queue.get_nowait()
            except Queue.Empty:
                break

            if isinstance(task, list):
                _tasks = task
            else:
                _tasks = (task, )

            for task in _tasks:
                if not self.task_verify(task):
                    continue

                if task['taskid'] in self.projects[task['project']].task_queue:
                    if not task.get('schedule', {}).get('force_update', False):
                        logger.debug('ignore newtask %(project)s:%(taskid)s %(url)s', task)
                        continue

                if task['taskid'] in tasks:
                    if not task.get('schedule', {}).get('force_update', False):
                        continue

                tasks[task['taskid']] = task

        for task in itervalues(tasks):
            self.on_request(task)

        return len(tasks)
823207
def make_cancel_request(repo_name, request_id, auth, dry_run=True):
    
    url = '{}/{}/request/{}'.format(SELF_SERVE, repo_name, request_id)

    if dry_run:
        LOG.info('We would make a DELETE request to %s.' % url)
        return None

    LOG.info("We're going to cancel the job at %s" % url)
    req = requests.delete(url, auth=auth, timeout=TCP_TIMEOUT)
    # TODO: add debug message with the canceled job_id URL. Find a way
    # to do that without doing an additional request.
    return req
1359634
async def cancel(self):
        """"""
        self.is_cancelled = True
        if self.future is not None:
            self.future.cancel()
        if self.task_process is not None:
            log.warning("Worker is shutting down, but a task is running. Terminating task")
            await self.task_process.worker_shutdown_stop()
706865
function(task) {

		if (this._active_tasks.indexOf(task) == -1) {

			this._active_tasks.push(task);

		}

		this._enable();

		if (!this.is_running) {
			this._enable();
			this.is_running = true;
		}

	}
774451
async def on_shutdown(app):
    """"""
    global is_shutting_down
    is_shutting_down = True
    for task in app["websockets"]:
        task.cancel()
        try:
            await task
        except asyncio.CancelledError:
            pass
138672
def stop_old_tasks
      # only works when deployment is blocking
      return unless @options[:wait]

      Thread.new do
        stop = Ufo::Stop.new(@service, @options.merge(mute: true))
        while true
          stop.log "checking for old tasks and waiting for 10 seconds"
          stop.run
          sleep 10
        end
      end
    end
663323
public boolean removeTaskByTaskId(String taskId, boolean isInterrupt) {
        ScheduledFuture<?> future = runningTask.get(taskId);
        boolean flag = future.cancel(isInterrupt);
        if (flag) {
            runningTask.remove(taskId);
        }
        return flag;
    }
391295
void cancelTasklet(final boolean mayInterruptIfRunning, final int taskletId) {
    lock.lock();
    try {
      // This is not ideal since we are using a linear time search on all the workers.
      final String workerId = getWhereTaskletWasScheduledTo(taskletId);
      if (workerId == null) {
        // launchTasklet called but not yet running.
        taskletsToCancel.add(taskletId);
        return;
      }

      if (mayInterruptIfRunning) {
        LOG.log(Level.FINE, "Cancelling running Tasklet with ID {0}.", taskletId);
        runningWorkers.get(workerId).cancelTasklet(taskletId);
      }
    } finally {
      lock.unlock();
    }
  }
192440
def task_stop(self, **kw):
        

        id, task = self.get_task(**kw)

        self._execute(id, 'stop')
        return self.get_task(uuid=task['uuid'])[1]
534581
private void notifyStoppedOrFailed(Throwable runException) {
        final Throwable stopException = this.stopException.get();
        if (runException == null) {
            // If runTask did not fail with an exception, see if we have a general stopException.
            runException = stopException;
        }

        if (runException instanceof CancellationException) {
            // CancellationExceptions are expected if we are shutting down the service; If this was the real
            // cause why runTask failed, then the service did not actually fail, so do not report a bogus exception.
            runException = null;
        }

        if (runException == null) {
            // Normal shutdown.
            notifyStopped();
        } else {
            if (stopException != null && stopException != runException) {
                // We have both a stopException and a runTask exception. Since the stopException came first, that is the
                // one we need to fail with, so add the runTask exception as suppressed.
                stopException.addSuppressed(runException);
                runException = stopException;
            }

            // Shutdown caused by some failure.
            notifyFailed(runException);

        }

        log.info("{}: Stopped.", this.traceObjectId);
    }
300475
function interceptTask(task, asyncTeardown) {
    var doneCallback;

    function interceptCallback(err, value) {
        function onTeardown(newErr) {
            doneCallback(err || newErr, value);
        }

        asyncTeardown(onTeardown);
    }

    if (typeof task === 'function') {
        doneCallback = task;
        return interceptCallback;
    } else {
        doneCallback = task.end.bind(task);
        task.end = interceptCallback;
        return task;
    }
}
256141
public final void cancel(CancelException reason) {
		if (cancelling != null)
			return;
		if (reason == null) reason = new CancelException("No reason given");
		cancelling = reason;
		if (TaskScheduler.cancel(this)) {
			status = Task.STATUS_DONE;
			result.cancelled(reason);
			return;
		}
		if (manager.remove(this)) {
			status = Task.STATUS_DONE;
			result.cancelled(reason);
			return;
		}
		if (status == Task.STATUS_NOT_STARTED) {
			status = Task.STATUS_DONE;
			result.cancelled(reason);
			return;
		}
	}
470032
def cancel(self):
        
        try:
            self.post("control", action="cancel")
        except HTTPError as he:
            if he.status == 404:
                # The job has already been cancelled, so
                # cancelling it twice is a nop.
                pass
            else:
                raise
        return self
195990
private void checkCancelRequestedFlag() {

		if (this.cancelRequested.compareAndSet(true, false)) {
			final TaskCancelResult tsr = cancelTask();
			if (tsr.getReturnCode() != AbstractTaskResult.ReturnCode.SUCCESS
				&& tsr.getReturnCode() != AbstractTaskResult.ReturnCode.TASK_NOT_FOUND) {
				LOG.error("Unable to cancel vertex " + this + ": " + tsr.getReturnCode().toString()
					+ ((tsr.getDescription() != null) ? (" (" + tsr.getDescription() + ")") : ""));
			}
		}
	}
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);

        }
    }