Estimate completion time for a task.

        :returns: deferred that when fired returns a datetime object for the
                  estimated, or the actual datetime, or None if we could not
                  estimate a time for this task method.
324763
def estimate_completion(self):
        
        if self.completion_ts:
            # Task is already complete. Return the exact completion time:
            defer.returnValue(self.completed)
        # Get the timestamps from the descendent task that's doing the work:
        if self.method == 'build' or self.method == 'image':
            subtask_completion = yield self.estimate_descendents()
            defer.returnValue(subtask_completion)
        if self.state == task_states.FREE:
            est_completion = yield self._estimate_free()
            defer.returnValue(est_completion)
        avg_delta = yield self.estimate_duration()
        if avg_delta is None:
            defer.returnValue(None)
        est_completion = self.started + avg_delta
        defer.returnValue(est_completion)
73591
function() {

		var time = new Date().getTime(),
			i = 0,
			count = this._active_tasks.length,
			task,
			active_tasks = [];

		for (; i < count; i++) {

			task = this._active_tasks[i];

			if (task.isRunning()) {
				task.onTimer(time);
				// note: at this moment task may be already off, but it's not checked - to save processor resources.
				active_tasks.push(task);
			}

		}

		if (!active_tasks.length) {

			this.is_running = false;

		}

		this._active_tasks = active_tasks;

	}
409851
def timeit(method):
    """"""

    import datetime

    @functools.wraps(method)
    def timed_method(self, rinput):

        time_start = datetime.datetime.utcnow()
        result = method(self, rinput)
        time_end = datetime.datetime.utcnow()
        result.time_it(time_start, time_end)
        self.logger.info('total time measured')
        return result

    return timed_method
74212
def has_ended(self):
        
        assessment_offered = self.get_assessment_offered()
        now = DateTime.utcnow()
        # There's got to be a better way to do this:
        if self._my_map['completionTime'] is not None:
            return True
        elif assessment_offered.has_deadline() and assessment_offered.has_duration():
            if self._my_map['actualStartTime'] is None:
                return now >= assessment_offered.get_deadline()
            else:
                return (now >= assessment_offered.get_deadline() and
                        now >= self._my_map['actualStartTime'] + assessment_offered.get_duration())
        elif assessment_offered.has_deadline():
            return now >= assessment_offered.get_deadline()
        elif assessment_offered.has_duration() and self._my_map['actualStartTime'] is not None:
            return now >= self._my_map['actualStartTime'] + assessment_offered.get_duration()
        else:
            return False
1049059
def timeit(func):
    

    @wraps(func)
    def _wrapper(*args, **kwargs):
        start = time.time()

        result = func(*args, **kwargs)

        elapsed = time.time() - start
        LOGGER.info('%s took %s seconds to complete', func.__name__, round(elapsed, 2))
        return result

    return _wrapper
223394
def duration(self):
        
        if self.end_datetime is None or self.start_datetime is None:
            return 0
        return (self.end_datetime - self.start_datetime).total_seconds()
713629
def wait(self):
        
        d = defer.Deferred()
        if self._result is None:
            self._waiters.append(d)
        else:
            self._fire_deferred(d)
        return d
867788
def getNewestCompleteTime(self):
        
        bldrid = yield self.getBuilderId()
        completed = yield self.master.data.get(
            ('builders', bldrid, 'buildrequests'),
            [resultspec.Filter('complete', 'eq', [False])],
            order=['-complete_at'], limit=1)
        if completed:
            return completed[0]['complete_at']
        else:
            return None
491016
def get(self):
        ''''''
        if self.bucket.get() < 1:
            return None
        now = time.time()
        self.mutex.acquire()
        try:
            task = self.priority_queue.get_nowait()
            self.bucket.desc()
        except Queue.Empty:
            self.mutex.release()
            return None
        task.exetime = now + self.processing_timeout
        self.processing.put(task)
        self.mutex.release()
        return task.taskid
1325566
def delta(self):
        
        completed_date = parse_api_datetime(self.batch["CompletedDate"])
        created_date = parse_api_datetime(self.batch["CreatedDate"])
        td = completed_date - created_date
        return td.total_seconds()
922215
def _getAbsoluteTime(self, start, delay):
        
        return start + datetime.timedelta(days=0, seconds=delay)
1091296
def progress(self, *restrictions, display=True):
        
        todo = self._jobs_to_do(restrictions)
        total = len(todo)
        remaining = len(todo - self.target)
        if display:
            print('%-20s' % self.__class__.__name__,
                  'Completed %d of %d (%2.1f%%)   %s' % (
                      total - remaining, total, 100 - 100 * remaining / (total+1e-12),
                      datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')), flush=True)
        return remaining, total
398729
def get(self):
        
        try:
            item = self._queue.get_nowait()
        except (Empty, PersistEmpty):
            return None

        if self._persistence_path:
            self._queue.task_done()

        return item
1016831
def remaining_time(self):
        
        elapsed_time = (datetime.datetime.now() - self.start_time).total_seconds()
        # safety to avoid devision by zero
        if self.progress == 0:
            self.progress = 1

        estimated_total_time = 100. / self.progress * elapsed_time

        return datetime.timedelta(seconds = max(estimated_total_time - elapsed_time, 0))
676136
def _function(self):
        

        start_time = datetime.datetime.now()

        # calculate stop time
        if self.settings['wait_mode'] == 'absolute':
            stop_time = start_time + datetime.timedelta(seconds= self.settings['wait_time'])
        elif self.settings['wait_mode'] == 'loop_interval':
            if self.last_execution is None:
                stop_time = start_time
            else:
                loop_time = start_time - self.last_execution
                wait_time = datetime.timedelta(seconds= self.settings['wait_time'])
                if wait_time.total_seconds() <0:
                    stop_time = start_time
                else:
                    stop_time = start_time + wait_time
        else:
            TypeError('unknown wait_mode')

        current_time = start_time
        while current_time<stop_time:
            if self._abort:
                break
            current_time = datetime.datetime.now()

            time.sleep(1)

            self.progress = 100.*(current_time- start_time).total_seconds() / (stop_time - start_time).total_seconds()
            self.updateProgress.emit(int(self.progress))

        if self.settings['wait_mode'] == 'absolute':
            self.last_execution = None
        else:
            self.last_execution = start_time
95107
def elapsed(self):
        
        if not self.start_date:
            return None
        return (self.end_date or datetime.utcnow()) - self.start_date
521955
def missing_datetimes(self, finite_datetimes):
        
        return [d for d in finite_datetimes if not self._instantiate_task_cls(self.datetime_to_parameter(d)).complete()]