Called when an existing task is removed from the configuration.
        This sets a Do Not Resuscitate flag and then initiates a stop
        sequence.  Once all processes have stopped, the task will delete
        itself.
166147
def terminate(self):
        
        log = self._params.get('log', self._discard)
        self._dnr = time.time()
        self.stop()
        log.info("Task '%s' marked for death", self._name)
1010221
private void invokeCleanup(DockerClient client, List<String> builtImages, @Nonnull Set<String> containers) {
        PrintStream llog = taskListener.getLogger();

        if (cleanupDangling) {
            for (String containerId : containers) {
                try {
                    client.removeImageCmd(containerId)
                            .exec();
                    llog.printf("Removed dangling layer image %s.%n", containerId);
                    LOG.debug("Removed dangling layer image '{}'", containerId);
                } catch (NotFoundException | ConflictException ex) {
                    // ignore
                } catch (Throwable ex) {
                    taskListener.error("Can't remove dangling layer image " + containerId + ".");
                    LOG.error("Can't remove dangling layer image " + containerId, ex);
                }
            }
        }

        if (!cleanup) {
            llog.println("Skipping cleanup.");
            return;
        } else {
            llog.println("Running cleanup...");
        }

        for (String image : builtImages) {
            if (isNotEmpty(image)) {
                llog.println("Removing built image " + image);
                try {
                    client.removeImageCmd(image)
                            .exec();
                } catch (NotFoundException ex) {
                    llog.println("Image doesn't exist.");
                } catch (Throwable ex) {
                    taskListener.error("Can't remove image" + ex.getMessage());
                    //ignore as it cleanup
                }
            }
        }
    }
246435
synchronized void cleanUpOverMemoryTask(TaskAttemptID tid, boolean wasFailure,
      String diagnosticMsg) {
    TaskInProgress tip = runningTasks.get(tid);
    if (tip != null) {
      tip.reportDiagnosticInfo(diagnosticMsg);
      try {
        purgeTask(tip, wasFailure); // Marking it as failed/killed.
      } catch (IOException ioe) {
        LOG.warn("Couldn't purge the task of " + tid + ". Error : " + ioe);
      }
    }
  }
903243
@SuppressWarnings("deprecation")
    public boolean cancel(boolean sync) {

        boolean success = false;

        try {
            switch (state) {
            case WAITING:
                ParallelTaskManager.getInstance().removeTaskFromWaitQ(this);
                this.state = ParallelTaskState.COMPLETED_WITHOUT_ERROR;
                success = true;
                break;
            case IN_PROGRESS:
                if (executionManager != null
                        && !executionManager.isTerminated()) {

                    executionManager.tell(ExecutionManagerMsgType.CANCEL,
                            executionManager);
                    logger.info(
                            "Asked parallel task {} to stop from running...",
                            this.taskId);

                    if (sync) {
                        logger.info("Run cancel in SYNC mode... waiting for task to finish...");
                        while (!isCompleted()) {
                            try {
                                Thread.sleep(100L);
                            } catch (InterruptedException e) {
                                logger.error(" task {} interrupted ", this.taskId);
                            }
                        }
                        logger.info("Task completed! Cancellation is completed.");
                    } else {
                        logger.info("Run cancel in ASYNC mode... will now return...");
                    }

                } else {
                    logger.info("manager already killed or not exist..");
                }
                this.state = ParallelTaskState.COMPLETED_WITH_ERROR;
                success = true;
                break;
            case COMPLETED_WITHOUT_ERROR:
            case COMPLETED_WITH_ERROR:
                logger.info("task are already in completed state..no operation...");
                success = true;
                break;
            default:
                break;

            }

        } catch (Exception e) {
            logger.error("cancel task {} error with exception details ",
                    this.getTaskId(), e);
        }

        return success;
    }
884627
def CompleteTask(self, task):
    
    with self._lock:
      if task.identifier not in self._tasks_merging:
        raise KeyError('Task {0:s} was not merging.'.format(task.identifier))

      self.SampleTaskStatus(task, 'completed')

      del self._tasks_merging[task.identifier]

      logger.debug('Completed task {0:s}.'.format(task.identifier))
367769
public void resetTask () {
		if (status == Status.RUNNING) cancel();
		for (int i = 0, n = getChildCount(); i < n; i++) {
			getChild(i).resetTask();
		}
		status = Status.FRESH;
		tree = null;
		control = null;
	}
279085
synchronized void removeServerProcess() {
        this.requiredState = InternalState.STOPPED;
        internalSetState(new ProcessRemoveTask(), InternalState.STOPPED, InternalState.PROCESS_REMOVING);
    }
1002940
def close(self) -> None:
        
        if self.close_task is None:
            self.close_task = self.loop.create_task(self._close())
1297114
def _remove_dead_greenlet(self, task_name):
        '''
        
        '''
        for greenlet in self.active[task_name]:
            try:
                # Allows active greenlet continue to run
                if greenlet.dead:
                    self.active[task_name].remove(greenlet)
            except BaseException:
                pass
78026
public void delete() throws IOException, InterruptedException {
        checkPermission(DELETE);
        boolean responsibleForAbortingBuilds = !ItemDeletion.contains(this);
        boolean ownsRegistration = ItemDeletion.register(this);
        if (!ownsRegistration && ItemDeletion.isRegistered(this)) {
            // we are not the owning thread and somebody else is concurrently deleting this exact item
            throw new Failure(Messages.AbstractItem_BeingDeleted(getPronoun()));
        }
        try {
            // if a build is in progress. Cancel it.
            if (responsibleForAbortingBuilds || ownsRegistration) {
                Queue queue = Queue.getInstance();
                if (this instanceof Queue.Task) {
                    // clear any items in the queue so they do not get picked up
                    queue.cancel((Queue.Task) this);
                }
                // now cancel any child items - this happens after ItemDeletion registration, so we can use a snapshot
                for (Queue.Item i : queue.getItems()) {
                    Item item = Tasks.getItemOf(i.task);
                    while (item != null) {
                        if (item == this) {
                            queue.cancel(i);
                            break;
                        }
                        if (item.getParent() instanceof Item) {
                            item = (Item) item.getParent();
                        } else {
                            break;
                        }
                    }
                }
                // interrupt any builds in progress (and this should be a recursive test so that folders do not pay
                // the 15 second delay for every child item). This happens after queue cancellation, so will be
                // a complete set of builds in flight
                Map<Executor, Queue.Executable> buildsInProgress = new LinkedHashMap<>();
                for (Computer c : Jenkins.getInstance().getComputers()) {
                    for (Executor e : c.getAllExecutors()) {
                        final WorkUnit workUnit = e.getCurrentWorkUnit();
                        final Executable executable = workUnit != null ? workUnit.getExecutable() : null;
                        final SubTask subtask = executable != null ? getParentOf(executable) : null;
                                
                        if (subtask != null) {        
                            Item item = Tasks.getItemOf(subtask);
                            if (item != null) {
                                while (item != null) {
                                    if (item == this) {
                                        buildsInProgress.put(e, e.getCurrentExecutable());
                                        e.interrupt(Result.ABORTED);
                                        break;
                                    }
                                    if (item.getParent() instanceof Item) {
                                        item = (Item) item.getParent();
                                    } else {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                if (!buildsInProgress.isEmpty()) {
                    // give them 15 seconds or so to respond to the interrupt
                    long expiration = System.nanoTime() + TimeUnit.SECONDS.toNanos(15);
                    // comparison with executor.getCurrentExecutable() == computation currently should always be true
                    // as we no longer recycle Executors, but safer to future-proof in case we ever revisit recycling
                    while (!buildsInProgress.isEmpty() && expiration - System.nanoTime() > 0L) {
                        // we know that ItemDeletion will prevent any new builds in the queue
                        // ItemDeletion happens-before Queue.cancel so we know that the Queue will stay clear
                        // Queue.cancel happens-before collecting the buildsInProgress list
                        // thus buildsInProgress contains the complete set we need to interrupt and wait for
                        for (Iterator<Map.Entry<Executor, Queue.Executable>> iterator =
                             buildsInProgress.entrySet().iterator();
                             iterator.hasNext(); ) {
                            Map.Entry<Executor, Queue.Executable> entry = iterator.next();
                            // comparison with executor.getCurrentExecutable() == executable currently should always be
                            // true as we no longer recycle Executors, but safer to future-proof in case we ever
                            // revisit recycling.
                            if (!entry.getKey().isAlive()
                                    || entry.getValue() != entry.getKey().getCurrentExecutable()) {
                                iterator.remove();
                            }
                            // I don't know why, but we have to keep interrupting
                            entry.getKey().interrupt(Result.ABORTED);
                        }
                        Thread.sleep(50L);
                    }
                    if (!buildsInProgress.isEmpty()) {
                        throw new Failure(Messages.AbstractItem_FailureToStopBuilds(
                                buildsInProgress.size(), getFullDisplayName()
                        ));
                    }
                }
            }
            synchronized (this) { // could just make performDelete synchronized but overriders might not honor that
                performDelete();
            } // JENKINS-19446: leave synch block, but JENKINS-22001: still notify synchronously
        } finally {
            if (ownsRegistration) {
                ItemDeletion.deregister(this);
            }
        }
        getParent().onDeleted(AbstractItem.this);
        Jenkins.getInstance().rebuildDependencyGraphAsync();
    }
340208
def do_cancel(self, taskid: int) -> None:
        """"""
        task = task_by_id(taskid, self._loop)
        if task:
            fut = asyncio.run_coroutine_threadsafe(
                cancel_task(task), loop=self._loop)
            fut.result(timeout=3)
            self._sout.write('Cancel task %d\n' % taskid)
        else:
            self._sout.write('No task %d\n' % taskid)
690132
function cancelTask(proc, taskId) {
  const taskProcs = proc.tasks[taskId];
  delete proc.tasks[taskId];

  for (const execId in taskProcs) {
    const taskCall = taskProcs[execId];
    if (taskCall && taskCall.cancel) {
      taskCall.cancel();
    }
  }
}
1132065
protected void reset() {
		if (this.status == ProcessStatus.STOPPED || this.status == ProcessStatus.COMPLETED) {
			if (this.runOnce) {
				throw new UnsupportedOperationException("This process template can only safely execute once; "
						+ "instantiate a new instance per request");
			}

			this.status = ProcessStatus.RESET;
		}
	}
1190174
private void onUncleanExit(final String processId, final int exitCode) {
    this.onResourceStatus(
        ResourceStatusEventImpl.newBuilder()
            .setIdentifier(processId)
            .setState(State.FAILED)
            .setExitCode(exitCode)
            .build()
    );
  }
138061
public final void cancel ()
    {
        IntervalTask task = _task;
        if (task != null) {
            _task = null;
            task.cancel();
        }
    }
260924
public void stopChecking() {
        // synchronize with other attempts to update the running task
        synchronized(runningTaskLock){
            if(runningTask != null) {
                // cancel task (let it complete its current run if running)
                runningTaskFuture.cancel(false);
                // log
                LOGGER.debug("Stop criterion checker for search {} deactivated", search);
                // discard task
                runningTask = null;
                runningTaskFuture = null;
            }
        }
    }
432101
public void remove(final Task task)
  {
    giant.lock();
    try {
      try {
        log.info("Removing task[%s] from activeTasks", task.getId());
        for (final TaskLockPosse taskLockPosse : findLockPossesForTask(task)) {
          unlock(task, taskLockPosse.getTaskLock().getInterval());
        }
      }
      finally {
        activeTasks.remove(task.getId());
      }
    }
    finally {
      giant.unlock();
    }
  }