/*
Tries and runs the task. Note that if the task is already running, it will wait
until it finished running, and then run it again. The delay option does not apply here.
185817
function doRun(onDone) {
  var acts = [],
    self = this;
  this.__running = true;
  for(var i=0; i < this.__queue.length; i++) {
    var key = this.__queue[i];
    acts.push({name: key, fn: this.__actions[key]});
  }
  var interval = null,
    currentAction = null;
  if(this.__options.timeout > 0) {
    interval = setTimeout(function() {
      hasTimedout = true;
      var err = new Error('Task action has timed out.');
      err.action = currentAction;
      err.code = 'TIMEOUT';
      interval = null;
      onActionComplete(err);
    }, this.__options.timeout * 1000);
  }

  var calls = [],
    hasTimedout = false,
    results = [];
  var taskCtx = {};
  for(var key in CONTEXT) {
    taskCtx[key] = CONTEXT[key];
  }
  _.forEach(acts, function(action) {
    if(typeof action.fn !== 'function') {
      log.warn('Crux.tasks: [%s] Action %s was scheduled but not defined. Skipping.', self.name, action.name);
      return;
    }
    calls.push(function AsyncAction(done) {
      currentAction = action.name;
      if(hasTimedout) return done();
      if(self.debug) {
        log.info('Crux.tasks: [%s] running: %s', self.name, action.name);
      }
      try {
        var pObj = action.fn.apply(taskCtx, results);
      } catch(e) {
        log.warn('Crux.tasks: [%s] Action %s threw an exception.', self.name, action.name);
        log.debug(e);
        return done(e);
      }
      if(typeof pObj !== 'object' || !pObj || typeof pObj.then !== 'function') {
        // Not a promise, synchronous call.
        results.push(pObj);
        return done();
      }
      pObj.then(function(res) {
        results.push(typeof res === 'undefined' ? null : res);
        done();
      }).catch(function(err) {
        if(typeof err !== 'object' || !err) err = new Error('Task action failed');
        err.action = action.name;
        done(err);
      });
    });
  });

  function cleanupAndContinue() {
    results = null;
    taskCtx = null;
    self.emit('run'); // the run event
    if(self.__run_queue.length === 0) return;
    var fn = self.__run_queue[0];
    self.__run_queue.splice(0,1);
    doRun.call(self, fn);
  }

  function onActionComplete(err) {
    self.__running = false;
    var handlerName = '';
    if(err) {
      if(err.code === 'TIMEOUT') {
        handlerName = 'timeout';
      } else {
        handlerName = 'failed';
      }
      return self.runHandler(handlerName, err, taskCtx, function() {
        self.emit(handlerName, err, taskCtx);
        onDone && onDone(err);
        cleanupAndContinue();
      });
    } else {
      self.runHandler('completed', results, taskCtx, function() {
        self.emit('completed', results, taskCtx);
        onDone && onDone(null, results);
        cleanupAndContinue();
      });
    }
  }
  var asyncCall = (self.type === 'serial' ? 'series' : 'parallel');
  async[asyncCall](calls, function(err) {
    clearTimeout(interval);
    if(hasTimedout) return;
    onActionComplete(err);
  });
}
760434
private synchronized void mainLoop() {
        for (Task task: taskDao.listTasks()) {
            if (task.getState().equals(Task.STARTING)) {
                startTask(task);
            } else if (task.getState().equals(Task.PAUSING)) {
                pauseTask(task);
            } else if (task.getState().equals(Task.RESUMING)) {
                resumeTask(task);
            } else if (task.getState().equals(Task.CANCELING)) {
                cancelTask(task);
            }
        }
        try {
            wait(POLL_SECONDS * 1000);
        } catch (InterruptedException e) {
        }
    }
344777
async def run_task(self, container, task, newthread = False):
        ""
        e = TaskEvent(self, task=task, newthread = newthread)
        await container.wait_for_send(e)
        ev = await TaskDoneEvent.createMatcher(e)
        if hasattr(ev, 'exception'):
            raise ev.exception
        else:
            return ev.result
312075
public void run() {
		
		final TimerTaskData taskData = task.getData();
		final Serializable taskID = taskData.getTaskID();
		
		if (logger.isDebugEnabled()) {
			logger.debug("Cancelling timer task for timer ID "+taskID);
		}
		
		scheduler.getLocalRunningTasksMap().remove(taskID);
		
		try {
			task.cancel();					
		}
		catch (Throwable e) {
			logger.error(e.getMessage(),e);
		}
	}
738066
private void runSelectTask()
  {
    if (_lifecycle.isActive() || _lifecycle.isAfterStopping()) {
      log.warning(this + " cannot start because an instance is active");
      return;
    }

    initNative(_fd);

    synchronized (_thread) {
      _thread.notify();
    }

    if (! _lifecycle.toActive()) {
      log.warning(this + " invalid starting state");
      return;
    }

    runImpl();
  }
1227515
async def run_task(self) -> None:
        ''''''

        while self.running:
            try:
                Log.debug('executing periodic task %s', self.name)
                before = self.time()
                await self.run()
                total = self.time() - before
                Log.debug('finished periodic task %s in %.1f seconds',
                          self.name, total)

                sleep = self.INTERVAL - total
                if sleep > 0:
                    await self.sleep(sleep)

            except CancelledError:
                Log.debug('cancelled periodic task %s', self.name)
                raise

            except Exception:
                Log.exception('exception in periodic task %s', self.name)
528031
@Override
    public void run() {
        try {
            if (this.isDone()) {
                return;
            }
            ExpeditedFutureTask<V> futureTask = new ExpeditedFutureTask<V>(this.m_callable);
            this.m_defaultFuture = futureTask;
            this.m_executor.execute(futureTask);
            this.m_scheduledExecutorQueue.remove(this);
        } catch (Exception e) {
            this.m_pendingException = new RuntimeException(e);
            return;
        } finally {
            // Let blocked ScheduleFuture methods thru now.
            this.m_coordinationLatch.countDown();
        }
    }
8385
function startRequested() {
		var start = [];

		if (run.length) {
			run.forEach(function(task) {
				var exists = task.replace(/:.*$/, '') in definitions.task;

				console.log(
					'Task %s %s',
					exists ? chalk.green(task) : chalk.red(task),
					exists ? 'running' : 'not found!'
				);

				if (exists) {
					start.push(task);
				}
			});

			if (start.length) {
				gulp.start.apply(gulp, start.concat([function(error) {
					if (error) {
						throw new Error(error);
					}

					console.log('Complete');
				}]));
			}
			else {
				console.log(chalk.red('No tasks are running, exiting!'));
				process.exit(1);
			}
		}

		return !!start.length;
	}
837053
public void run() {
    try {
      startCleanupThreads();
      try {
        // This while-loop attempts reconnects if we get network errors
        while (running && !shuttingDown) {
          try {
            State osState = offerService();
            if (osState == State.STALE || osState == State.DENIED) {
              // Shutdown TaskTracker instead of reinitialize.
              // TaskTracker should be restarted by external tools.
              LOG.error("offerService returns " + osState + ". Shutdown. ");
              break;
            }
          } catch (Exception ex) {
            if (!shuttingDown) {
              LOG.info("Lost connection to JobTracker [" +
                  jobTrackAddr + "].  Retrying...", ex);
              try {
                Thread.sleep(5000);
              } catch (InterruptedException ie) {
              }
            }
          }
        }
      } finally {
        shutdown();
      }
    } catch (IOException iex) {
      LOG.error("Got fatal exception while initializing TaskTracker", iex);
      return;
    }
  }
265376
@Override
    public String start() {
        if (mConsumed) {
            throw new IllegalStateException("task has been executed already");
        }
        if (Config.DEBUG) {
            Log.v(TAG, "start() " + getName());
        }
        mConsumed = true;
        final Runnable runnable = new Runnable() {
            @Override
            public void run() {
                execute();
            }
        };
        final long delayMillis = mInfo.delayMillis;
        if (delayMillis > 0) {
            mInfo.handler.postDelayed(runnable, delayMillis);
        } else {
            runnable.run();
        }
        return getName();
    }
418699
async def run_task(self) -> None:
        ''''''

        while self.running:
            try:
                item = self.QUEUE.get_nowait()

                Log.debug('%s processing work item', self.name)
                await self.run(item)

                Log.debug('%s completed work item', self.name)
                self.QUEUE.task_done()

            except asyncio.QueueEmpty:
                if self.OPEN:
                    await self.sleep(0.05)

                else:
                    Log.debug('%s queue closed and empty, stopping', self.name)
                    return

            except CancelledError:
                Log.debug('%s cancelled, dropping work item')
                self.QUEUE.task_done()
                raise

            except Exception:
                Log.exception('%s failed work item', self.name)
                self.QUEUE.task_done()
797535
@Override
    public final void run() {
        String taskID = m_taskRecord.getTaskID();
        m_logger.debug("Starting task '{}' in tenant '{}'", taskID, m_tenant);
        try {
            TaskManagerService.instance().registerTaskStarted(this);
            m_lastProgressTimestamp = System.currentTimeMillis();
            setTaskStart();
            execute();
            setTaskFinish();
        } catch (Throwable e) {
            m_logger.error("Task '" + taskID + "' failed", e);
            String stackTrace = Utils.getStackTrace(e);
            setTaskFailed(stackTrace);
        } finally {
            TaskManagerService.instance().registerTaskEnded(this);
        }
    }
1126678
@Override
	public void run() {
		Stopwatch stopwatch = SimonManager.getStopwatch(NAME);
		try (Split ignored = stopwatch.start();) {
			sleep(SLEEP);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		// signal to latch that the thread is finished
		latch.countDown();
	}
246250
async function run(task, action, ...args) {
  const command = process.argv[2]
  const taskName =
    command && !command.startsWith('-') ? `${task} ${command}` : task
  const start = new Date()
  process.stdout.write(`Starting '${taskName}'...\n`)
  try {
    await action(...args)
    process.stdout.write(
      `Finished '${taskName}' after ${new Date().getTime() -
        start.getTime()}ms\n`
    )
  } catch (error) {
    process.stderr.write(`${error.stack}\n`)
  }
}
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);
        }
    }
453042
private static Runnable nextTask() {
		synchronized (lock) {
			// Block until we have another object in the queue to execute.
			while (taskList.isEmpty()) {
				try {
					lock.wait();
				} catch (InterruptedException ie) {
				}
			}
			return (Runnable) taskList.removeLast();
		}
	}
308391
@Override
    public void run()
    {
        m_taskQueue.offer(this);
        // check if previous task is running for more than threshold
        SiteTasker task = m_taskQueue.peek();
        long currentTime = System.nanoTime();
        long headOfQueueOfferTime;
        if (task != null) {
            headOfQueueOfferTime = task.getQueueOfferTime();
        } else {
            headOfQueueOfferTime = currentTime;
        }
        if (headOfQueueOfferTime != m_previousTaskTimestamp) {
            m_previousTaskTimestamp = headOfQueueOfferTime;
            m_previousTaskPeekTime = currentTime;
        } else if (currentTime - m_previousTaskPeekTime >= m_procedureLogThreshold) {
            long waitTime = (currentTime - m_previousTaskPeekTime)/1_000_000_000L; // in seconds
            if (m_logger.isDebugEnabled()) {
                String taskInfo = (task == null) ? "" : " Task Info: " + task.getTaskInfo();
                m_logger.rateLimitedLog(SUPPRESS_INTERVAL, Level.DEBUG, null, TICK_MESSAGE + taskInfo, waitTime, m_partitionId);
            } else {
                m_logger.rateLimitedLog(SUPPRESS_INTERVAL, Level.INFO, null, TICK_MESSAGE, waitTime, m_partitionId);
            }
        }
    }