There might be a race between {@link #run(Task)} and this method, but it shouldn't happen in real applications
because this method is called only in unit tests. See TaskLifecycleTest.

@param taskid task ID to clean up resources for
351925
@Override
  public void shutdown(final String taskid, String reason)
  {
    log.info("Shutdown [%s] because: [%s]", taskid, reason);
    if (runningItem != null && runningItem.getTask().getId().equals(taskid)) {
      runningItem.getResult().cancel(true);
    }
  }
1322565
public static void invokeTask (String name, Task task, TaskObserver observer)
    {
        // create a task runner and stick it in our task table
        TaskRunner runner = new TaskRunner(name, task, observer);
        _tasks.put(name, runner);
        // then start the runner up
        runner.start();
    }
209251
public void removeAll(TaskAttemptID taskId) throws IOException {
    String toBeDeleted =
      TaskTracker.getIntermediateOutputDir(jobId.toString(), taskId.toString());
    if (asyncDiskService != null) {
      asyncDiskService.moveAndDeleteFromEachVolume(toBeDeleted);
      LOG.info("Move and then delete map ouput " +
               toBeDeleted + " for task " + taskId);
      return;
    }
    LOG.info("Delete map ouput " + toBeDeleted + " for task " + taskId);
    conf.deleteLocalFiles(toBeDeleted);
  }
8797
public void runTask(Handler<Task> task) {
    if (currentTask == null) {
      currentTask = new Task(this);
      task.handle(currentTask);
    } else {
      queue.add(task);
    }
  }
143633
public void removeTaskFromQueue(String taskType, String taskId) {
        Preconditions.checkArgument(StringUtils.isNotBlank(taskType), "Task type cannot be blank");
        Preconditions.checkArgument(StringUtils.isNotBlank(taskId), "Task id cannot be blank");
        stub.removeTaskFromQueue(
                TaskServicePb.RemoveTaskRequest.newBuilder()
                        .setTaskType(taskType)
                        .setTaskId(taskId)
                        .build()
        );
    }
877146
protected void initNewTask(final int taskID)
	{

		this.articleID = taskID;

		this.partCounter = 0;
		this.revisionCounter = 0;

		this.revPrevious = null;
		this.revCurrent = null;
	}
252066
public static void runUITask(Object context, int uiTaskId, final Object... args) {

		if(!ProfileService.getInstance(context).isActive(context, Profile.THREADING)) {
		
			StringBuilder builder = new StringBuilder()
			.append("UI task with ID ")
			.append(uiTaskId)
			.append("cannot be run since the threading profile is inactive.");
			
			Log.w("Async task cannot ", builder.toString());
			
			return;
		}
		
		TaskManagers.UI.execute(context, uiTaskId, args);
	}
703536
public void executeInIoThread(Runnable task, boolean alwaysAsync) {
        if (!alwaysAsync && isIoThread()) {
            task.run();
        } else {
            registerTask(task);
        }
    }
659551
@Override
  public <T> T run(long timeout,
                   TimeUnit unit,
                   Consumer<Result<T>> task)
  {
    return delegate().run(timeout, unit, task);
  }
579083
public void start(String taskName) throws IllegalStateException {
		if (this.running) {
			throw new IllegalStateException("Can't start StopWatch: it's already running");
		}
		this.startTimeMillis = System.currentTimeMillis();
		this.running = true;
		this.currentTaskName = taskName;
	}
145673
public void completed(TaskAttemptID taskid) {
    //
    // Record that this taskid is complete
    //
    completedTask(taskid, TaskStatus.State.SUCCEEDED);
        
    // Note the successful taskid
    setSuccessfulTaskid(taskid);
    
    //
    // Now that the TIP is complete, the other speculative 
    // subtasks will be closed when the owning tasktracker 
    // reports in and calls shouldClose() on this object.
    //

    this.completes++;
    this.execFinishTime = JobTracker.getClock().getTime();
    recomputeProgress();
    
  }
18429
@Override
	public boolean registerTaskManager(final ResourceID resourceID) {

		componentMainThreadExecutor.assertRunningInMainThread();

		log.debug("Register new TaskExecutor {}.", resourceID);
		return registeredTaskManagers.add(resourceID);
	}
807440
@GuardedBy("evictionLock")
    void runTasksInChain(Task task) {
        while (task != null) {
            Task current = task;
            task = task.getNext();
            current.setNext(null);
            current.run();
        }
    }
979105
public void task_domain_id_accelerate_POST(Long id) throws IOException {
		String qPath = "/me/task/domain/{id}/accelerate";
		StringBuilder sb = path(qPath, id);
		exec(qPath, "POST", sb.toString(), null);
	}
1131847
public void run() {
		
		task.setSetTimerTransactionalAction(null);
		
		if (!canceled) {
			
			TimerTask previousTask = scheduler.getLocalRunningTasksMap().putIfAbsent(task.getData().getTaskID(), task);
			if(previousTask != null) {
				if (logger.isDebugEnabled()) {
					logger.debug("A task with id " + task.getData().getTaskID() + " has already been added to the local tasks, not rescheduling");
				}
			}
			
			final TimerTaskData taskData = task.getData();
			// calculate delay
			long delay = taskData.getStartTime() - System.currentTimeMillis();
			if (delay < 0) {
				delay = 0;
			}
			
			try {
				// schedule runnable
				if (taskData.getPeriod() < 0) {
					if (logger.isDebugEnabled()) {
						logger.debug("Scheduling one-shot timer with id "
								+ task.getData().getTaskID() + ", delay " + delay);
					}
					task.setScheduledFuture(scheduler.getExecutor().schedule(task, delay, TimeUnit.MILLISECONDS));
				} else {
					if (logger.isDebugEnabled()) {
						logger.debug("Scheduling periodic timer with id "
								+ task.getData().getTaskID() + ", scheduling strategy " + taskData.getPeriodicScheduleStrategy() + ", delay " + delay + ", period " + taskData.getPeriod());
					}
					if (taskData.getPeriodicScheduleStrategy() == PeriodicScheduleStrategy.withFixedDelay) {
						task.setScheduledFuture(scheduler.getExecutor().scheduleWithFixedDelay(task, delay, taskData.getPeriod(),TimeUnit.MILLISECONDS));
					}
					else {
						// default
						task.setScheduledFuture(scheduler.getExecutor().scheduleAtFixedRate(task, delay, taskData.getPeriod(),TimeUnit.MILLISECONDS));
					}					
				}		
			} catch (Throwable e) {
				logger.error(e.getMessage(), e);
				scheduler.remove(taskData.getTaskID(),true);
			}
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("Canceled scheduling periodic timer with id "
						+ task.getData().getTaskID());
			}
		}
	}
956425
@Override
  public void run() {
    try {
      // Change state and inform the Driver
      this.taskLifeCycleHandlers.beforeTaskStart();

      LOG.log(Level.FINEST, "Informing registered EventHandler<TaskStart>.");
      this.currentStatus.setRunning();

      // Call Task.call()
      final byte[] result = this.runTask();

      // Inform the Driver about it
      this.currentStatus.setResult(result);

      LOG.log(Level.FINEST, "Informing registered EventHandler<TaskStop>.");
      this.taskLifeCycleHandlers.afterTaskExit();

    } catch (final TaskStartHandlerFailure taskStartHandlerFailure) {
      LOG.log(Level.WARNING, "Caught an exception during TaskStart handler execution.", taskStartHandlerFailure);
      this.currentStatus.setException(taskStartHandlerFailure.getCause());
    } catch (final TaskStopHandlerFailure taskStopHandlerFailure) {
      LOG.log(Level.WARNING, "Caught an exception during TaskStop handler execution.", taskStopHandlerFailure);
      this.currentStatus.setException(taskStopHandlerFailure.getCause());
    } catch (final TaskCallFailure e) {
      LOG.log(Level.WARNING, "Caught an exception during Task.call().", e.getCause());
      this.currentStatus.setException(e);
    }
  }
865573
public static void call(Runnable task) {
        try {
            call(() -> {
                task.run();
                return true;
            });
        } catch (Exception e) {
            // It's safe to throw unsafely here because the Callable we passed never throws a checked exception.
            Exceptions.throwUnsafely(e);
        }
    }