(internal) calls the next method of weaved tasks until they are finished
        or The ``Plumber`` instance is stopped see: ``Dagger.chinkup``.
504959
def _plunge(tasks, pausing, finish):
        
        # If no result received either not started or start & stop
        # could have been called before the plunger thread
        while True:
            if pausing():
                tasks.stop()
            try:
                tasks.next()
            except StopIteration:
                finish(pausing())
                break
952390
void afterCompletion(Task task) {
        boolean delayable = schedule(task);
        DrainStatus status = drainStatus.get();
        if (status.shouldDrainBuffers(delayable)) {
            tryToDrainBuffers();
        }
        notifyListener();
    }
329800
public void waitUntilFinished()
    {
        flushTermination();
        flushUpdate();
        flushInsert();
        shutdown();
        for (int i = 0; i < numberOfQueues; i++)
        {
            while (!executors[i].isTerminated())
            {
                try
                {
                    executors[i].awaitTermination(10000000, TimeUnit.SECONDS);
                }
                catch (InterruptedException e)
                {
                    // ignore
                }
            }
        }
        if (useBulkInsert)
        {
            bulkInsert();
        }
        logFinalResults();
        if (this.error != null)
        {
            if (error instanceof RuntimeException)
            {
                throw (RuntimeException) error;
            } else
            {
                throw new RuntimeException("One or more parallel tasks failed", this.error);
            }
        }
    }
743507
function _drainQueueStep(queue) {
    var fn = queue.shift();
    if (typeof fn !== "function") {
        fn._settlePromises();
    } else {
        var receiver = queue.shift();
        var arg = queue.shift();
        fn.call(receiver, arg);
    }
}
762737
def wait_until_done(opts={})
      raise "Threadz: thread deadlocked because batch job was never started" if @latent && !@started

      timeout = opts.key?(:timeout) ? opts[:timeout] : 0
      @sleeper.wait(timeout) unless completed?
      errors = self.job_errors
      if !errors.empty? && !@error_handler
        raise JobError.new(errors)
      end
    end
1367758
def finish(self):
        """"""
        if self._finished:
            raise RuntimeError("finish() called twice.  May be caused "
                               "by using async operations without the "
                               "@asynchronous decorator.")
        if not hasattr(self, '_stream_queue') or not self._stream_queue:
            raise RuntimeError("`_stream_queue` was not assigned, you should"
                               "call `write_stream_queue` to set.")

        # === Replace `if not self._headers_written` === #
        self.set_status(200)
        self.set_header("Content-Type", "text/event-stream")
        self.set_header("Cache-Control", "no-cache")
        self.set_header("Access-Control-Allow-Origin", "*")
        # ============================================== #

        self.request.connection.set_close_callback(None)

        # === Add before self.flush === #
        # Reset buffer
        self._write_buffer = []
        self._headers_written = False
        # ============================= #

        self.flush(include_footers=True)

        # === Add after self.flush === #
        self._write_buffer = self._stream_queue
        self.request.connection._write_buffer = self._stream_queue
        # ============================ #

        self.request.finish()
        self._log()
        self._finished = True
        self.on_finish()
        # Break up a reference cycle between this handler and the
        # _ui_module closures to allow for faster GC on CPython.
        self.ui = None
1025411
function tryCatchNextTick(object, method, args) {
  try {
    return method.apply(object, args);
  } catch (error) {
    process.nextTick(function () {
      throw error;
    });
  }
}
51303
def maybe_call_closing_deferred(self):
        

        if self._closing_deferred:
            self._closing_deferred.callback(self)
            self._closing_deferred = None
949052
def _call_next(self, handler_chain):
        

        def wrapped(*args, **kwargs):
            if len(handler_chain) == 1:
                return handler_chain[0](*args, **kwargs)
            else:
                return handler_chain[0](self._call_next(handler_chain[1:]),
                                        *args, **kwargs)

        return wrapped
1176015
function finish(err) {
      // Run callbacks when we have an error,
      // or when import parsing is complete.
      if (err || self.isParsed()) {
        // Cache the file after parsing:
        _.cacheFile(self);

        // Run all callbacks:
        for (var i=0; i < self._cb.length; i++) self._cb[i](err, self);
        self._cb = [];
      }
    }
538356
def on_finish(func, handler, args, kwargs):
    
    tracing = handler.settings.get('opentracing_tracing')
    tracing._finish_tracing(handler)

    return func(*args, **kwargs)
1320946
void shutdownNow() {
    shutdown = true;
    for (int i = 0; i < channels.length; i++) {
      // Initiate channel shutdown
      channels[i].shutdown();
    }
    for (int i = 0; i < channels.length; i++) {
      try {
        // Wait for channel termination
        channels[i].awaitTermination(1, TimeUnit.SECONDS);
      } catch (InterruptedException ie) {
        channels[i].shutdownNow();
      }
    }
    fixedThreadPool.shutdownNow();
  }
77524
@Override
  public void stopScheduling() {
    LOG.debug("Stopping compute engine");
    // Requesting all workers to stop
    for (ChainingCallback chainingCallback : chainingCallbacks) {
      chainingCallback.stop(false);
    }

    // Workers have 40s to gracefully stop processing tasks
    long until = System.currentTimeMillis() + gracefulStopTimeoutInMs;
    LOG.info("Waiting for workers to finish in-progress tasks");
    while (System.currentTimeMillis() < until && ceWorkerController.hasAtLeastOneProcessingWorker()) {
      try {
        Thread.sleep(200L);
      } catch (InterruptedException e) {
        LOG.debug("Graceful stop period has been interrupted: {}", e);
        Thread.currentThread().interrupt();
        break;
      }
    }

    if (ceWorkerController.hasAtLeastOneProcessingWorker()) {
      LOG.info("Some in-progress tasks did not finish in due time. Tasks will be stopped.");
    }

    // Interrupting the tasks
    for (ChainingCallback chainingCallback : chainingCallbacks) {
      chainingCallback.stop(true);
    }
  }
675460
def on_finish(self, func):
        '''
        '''
        if self._done.is_set():
            if self._failure is None:
                backend.schedule(func, args=(self._value,))
        else:
            self._cbacks.append(func)
972481
def _worker_handler(future, worker, pipe, timeout):
    
    result = _get_result(future, pipe, timeout)

    if isinstance(result, BaseException):
        if isinstance(result, ProcessExpired):
            result.exitcode = worker.exitcode

        future.set_exception(result)
    else:
        future.set_result(result)

    if worker.is_alive():
        stop_process(worker)
329560
public void stop() {
		if (stopped) {
			return;
		}
		this.stopped = true;
		log.info("Stopping spidering process by request.");
		
		if (this.paused) {
			// Have to resume first or we get a deadlock
			this.resume();
		}
		
		// Issue the shutdown command
		this.threadPool.shutdown();
		try {
			if (!this.threadPool.awaitTermination(2, TimeUnit.SECONDS)) {
				log.warn("Failed to await for all spider threads to stop in the given time (2s)...");
				for (Runnable task : this.threadPool.shutdownNow()) {
					((SpiderTask) task).cleanup();
				}
			}
		} catch (InterruptedException ignore) {
			log.warn("Interrupted while awaiting for all spider threads to stop...");
		}
		if (httpSender != null) {
			this.getHttpSender().shutdown();
			httpSender = null;
		}

		// Notify the controller to clean up memory
		controller.reset();
		this.threadPool = null;

		// Notify the listeners -- in the meanwhile
		notifyListenersSpiderComplete(false);
	}
1152401
def finish(self):
        
        super(InterruptibleMixin, self).finish()
        signal(SIGINT, self.original_handler)