Helper method to start the task and wait for completion.

        Mainly used when we are submitting the task via the shell without passing through a queue manager.
962360
def start_and_wait(self, *args, **kwargs):
        
        self.start(*args, **kwargs)
        retcode = self.wait()
        return retcode
603356
async def wait(self):
        
        while True:
            await self.eio.wait()
            await self.sleep(1)  # give the reconnect task time to start up
            if not self._reconnect_task:
                break
            await self._reconnect_task
            if self.eio.state != 'connected':
                break
761858
def execute_task(self, task, parent_result):
        
        task.before_run(parent_result)
        context = task.create_context(self.message_queue)
        pending_result = self.pool.apply_async(execute_task_async, (task.func, task.id, context))
        self.pending_results.append(pending_result)
589915
def runTask(self, task, timeout=None):
        
        # Initialize the task.
        task.initialize(self)

        # Start the task.
        task.start()

        # Lets other threads run
        time.sleep(0)

        # Wait for it to finish.
        res = task.wait(timeout=timeout)

        # Now we're done
        return res
641411
def start!
      wait

      logger.warn 'Tasks list is empty' if tasks.empty?
      tasks.each do |task|
        run_task(task)
        sleep post_task_sleep_time
      end

      scheduler.join
    rescue SystemExit, Interrupt
      logger.info 'Shutting down'
      scheduler.shutdown
    end
719543
async def start_task(self, task: Task) -> None:
        ''''''

        try:
            Log.debug('task %s starting', task.name)
            before = time.time()
            task.counters['last_run'] = before

            task.running = True
            self.running_tasks.add(task)
            await task.run_task()
            Log.debug('task %s completed', task.name)

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

        except Exception:
            Log.exception('unhandled exception in task %s', task.name)

        finally:
            self.running_tasks.discard(task)
            task.running = False
            task.task = None

            after = time.time()
            total = after - before
            task.counters['last_completed'] = after
            task.counters['duration'] = total
221668
public void run() {
        try {

            Queue<ParallelTask> waitQ = ParallelTaskManager.getInstance()
                    .getWaitQ();

            logger.debug(
                    "TASK_WAIT_Q: Current waitQ has task count: {} in Thread scheduler",
                    waitQ.size());

            final ParallelTask task = waitQ.peek();
            if (task != null) {

                int totalUsedCapacityBefore = ParallelTaskManager.getInstance()
                        .getTotalUsedCapacity();

                int capacityThisTask = task.capacityUsed();
                int capacityRemain = ParallecGlobalConfig.maxCapacity
                        - totalUsedCapacityBefore;
                int totalUsedCapacityNew = totalUsedCapacityBefore
                        + capacityThisTask;

                logger.info(
                        "TASK_WAIT_Q: Exists Task in WaitQ with head of queue task id {}"
                                + "....Current used capacity {}, and remaining capacity is {}",
                        task.getTaskId(), totalUsedCapacityBefore,
                        capacityRemain);
                // condition to add to the in progress map
                if (totalUsedCapacityNew <= ParallecGlobalConfig.maxCapacity) {
                    logger.info(
                            "TASK_WAIT_Q: Sufficent capacity. Execute new task from wait queue. Task capacity {}"
                                    + " with total used capacity is now {}, capacityRemain will be {}",
                            capacityThisTask, totalUsedCapacityNew,
                            ParallecGlobalConfig.maxCapacity
                                    - totalUsedCapacityNew);

                    waitQ.poll(); // dequeue
                    Runnable taskRunnable = new Runnable() {
                        @Override
                        public void run() {
                            ParallelTaskManager.getInstance()
                                    .generateUpdateExecuteTask(task);
                        }
                    };
                    new Thread(taskRunnable).start();
                } else {
                    logger.info(
                            "TASK_WAIT_Q: Skip execution new task. Insufficent capacity. "
                                    + "Head of queue task needs capacity {}. However capacityRemain is only {}.",
                            capacityThisTask, capacityRemain);
                }

            }

        } catch (Exception e) {
            logger.error("TASK_WAIT_Q: fail in EvalTaskInWaitQRunner ", e);
        }
    }
639049
def start(self) -> None:
        

        self._shutdown = False

        # Start listening (if server) / Open connection (if client)
        if isinstance(self._protocol, Server):
            self.create_task(self._async_listen)
        elif isinstance(self._protocol, Client):
            self.create_task(self._async_open)
        else:
            raise NotImplementedError
565408
async def open(self, wait_for_completion=True):
        
        await self.set_position(
            position=Position(position_percent=0),
            wait_for_completion=wait_for_completion)
273105
def join(self, timeout=None):
        
        if self._context.state == RUNNING:
            raise RuntimeError('The Pool is still running')
        if self._context.state == CLOSED:
            self._wait_queue_depletion(timeout)
            self.stop()
            self.join()
        else:
            self._context.task_queue.put(None)
            self._stop_pool()
171239
def start(self):
        
        logger.info('Starting task {0}'.format(self.name))
        self.reset()
        if self.hostname:
            host = self.parent_job.parent.get_host(self.hostname)
            if host:
                self.remote_ssh(host)
            else:
                self.remote_failure = True
        else:
            self.process = subprocess.Popen(self.command,
                                            shell=True,
                                            env=os.environ.copy(),
                                            stdout=self.stdout_file,
                                            stderr=self.stderr_file)

        self.started_at = datetime.utcnow()
        self._start_check_timer()
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
1370304
def start_task(self, method, *args, **kwargs):
        
        thread = threading.Thread(target=method, args=args, kwargs=kwargs)
        thread.is_daemon = False
        thread.start()
        self.threads.append(thread)
388713
public synchronized void waitForStart()
	throws ServerException,
	       ClientException,
	       IOException {
	    try {
	        while(!isStarted() && !hasError()) {
		        wait();
	        }
	    } catch(InterruptedException e) {
            // break
	    }
	    checkError();
    }
1145659
private void mainLoop() {
        for (@AutoreleasePool int i = 0;;) {
            try {
                TimerTask task;
                boolean taskFired;
                synchronized(queue) {
                    // Wait for queue to become non-empty
                    while (queue.isEmpty() && newTasksMayBeScheduled)
                        queue.wait();
                    if (queue.isEmpty())
                        break; // Queue is empty and will forever remain; die

                    // Queue nonempty; look at first evt and do the right thing
                    long currentTime, executionTime;
                    task = queue.getMin();
                    synchronized(task.lock) {
                        if (task.state == TimerTask.CANCELLED) {
                            queue.removeMin();
                            continue;  // No action required, poll queue again
                        }
                        currentTime = System.currentTimeMillis();
                        executionTime = task.nextExecutionTime;
                        if (taskFired = (executionTime<=currentTime)) {
                            if (task.period == 0) { // Non-repeating, remove
                                queue.removeMin();
                                task.state = TimerTask.EXECUTED;
                            } else { // Repeating task, reschedule
                                queue.rescheduleMin(
                                  task.period<0 ? currentTime   - task.period
                                                : executionTime + task.period);
                            }
                        }
                    }
                    if (!taskFired) // Task hasn't yet fired; wait
                        queue.wait(executionTime - currentTime);
                }
                if (taskFired)  // Task fired; run it, holding no locks
                    task.run();
            } catch(InterruptedException e) {
            }
        }
    }
814750
@Override
	public T call() throws Exception {
		logger.debug("task '{}' starting", id);		
		try {
			// do the real work 
			return task.execute();
		} finally {
			// signal that the task is complete
			logger.debug("task '{}' is complete (queue size: {})", id, queue.size());
			queue.offer(id);			
		}
	}
329157
def wait(self, task_id):
        
        data = {
            'action': 'wait',
            'id': task_id
        }
        self.__send_pyobj(data)
        task = self.__recv_pyobj(notimeout=True)
        return task