calculate the duration we actually paused for and then
        finish building the task result string
328736
def _stop(self):
        '''  '''
        duration = time.time() - self.start
        self.result['stop'] = str(datetime.datetime.now())
        self.result['delta'] = int(duration)

        if self.duration_unit == 'minutes':
            duration = round(duration / 60.0, 2)
        else:
            duration = round(duration, 2)

        self.result['stdout'] = "Paused for %s %s" % (duration, self.duration_unit)
201947
def elapsed():
    
    environ.abort_thread()
    step = _cd.project.get_internal_project().current_step
    r = _get_report()
    r.append_body(render.elapsed_time(step.elapsed_time))

    result = '[ELAPSED]: {}\n'.format(timedelta(seconds=step.elapsed_time))
    r.stdout_interceptor.write_source(result)
1088854
@Private
  @Override
  public void completed(final int pTaskletId, final TOutput result) {
    assert taskletId == pTaskletId;
    this.userResult = Optional.ofNullable(result);
    if (callbackHandler != null) {
      executor.execute(new Runnable() {
        @Override
        public void run() {
          callbackHandler.onSuccess(userResult.get());
        }
      });
    }
    this.countDownLatch.countDown();
  }
1087088
private Duration assignmentDuration(Task task, Duration work)
   {
      Duration result = work;

      if (result != null)
      {
         if (result.getUnits() == TimeUnit.PERCENT)
         {
            Duration taskWork = task.getWork();
            if (taskWork != null)
            {
               result = Duration.getInstance(taskWork.getDuration() * result.getDuration(), taskWork.getUnits());
            }
         }
      }
      return result;
   }
558374
public static void endDoing() {
    long elapsed = System.currentTimeMillis() - startTime;
    System.err.println("done [" + nf.format(((double) elapsed) / 1000) + 
                       " sec].");
  }
931170
def duration(self):
        
        if self._closed or \
                not self._result or \
                "duration" not in self._result:
            return -1
        return self._result.get("duration", 0)
697604
def _finish(self, ispausing):
        
        if ispausing:
            self.log.debug('%s paused' % repr(self))
        else:
            self._finished.set()
            self.log.debug('%s finished' % repr(self))
275443
def on_task_done(self, task):
        ''''''
        task['status'] = self.taskdb.SUCCESS
        task['lastcrawltime'] = time.time()

        if 'schedule' in task:
            if task['schedule'].get('auto_recrawl') and 'age' in task['schedule']:
                task['status'] = self.taskdb.ACTIVE
                next_exetime = task['schedule'].get('age')
                task['schedule']['exetime'] = time.time() + next_exetime
                self.put_task(task)
            else:
                del task['schedule']
        self.update_task(task)

        project = task['project']
        self._cnt['5m'].event((project, 'success'), +1)
        self._cnt['1h'].event((project, 'success'), +1)
        self._cnt['1d'].event((project, 'success'), +1)
        self._cnt['all'].event((project, 'success'), +1).event((project, 'pending'), -1)
        logger.info('task done %(project)s:%(taskid)s %(url)s', task)
        return task
256968
protected void refreshTaskCountsAndWaitTime(TaskType type, long now) {
    TaskInProgress[] allTips = getTasks(type);
    int finishedTips = 0;
    int runningTips = 0;
    int runningTaskAttempts = 0;
    long totalWaitTime = 0;
    long jobStartTime = this.getStartTime();
    for (TaskInProgress tip : allTips) {
      if (tip.isComplete()) {
        finishedTips += 1;
      } else if(tip.isRunning()) {
        runningTaskAttempts += tip.getActiveTasks().size();
        runningTips += 1;
      }
      if (tip.getExecStartTime() > 0) {
        totalWaitTime += tip.getExecStartTime() - jobStartTime;
      } else {
        totalWaitTime += now - jobStartTime;
      }
    }
    if (TaskType.MAP == type) {
      totalMapWaitTime = totalWaitTime;
      runningMapTasks = runningTaskAttempts;
      neededMapTasks = numMapTasks - runningTips - finishedTips
          + neededSpeculativeMaps();
      pendingMapTasks = numMapTasks - runningTaskAttempts
          - failedMapTIPs - finishedMapTasks + speculativeMapTasks;
    } else {
      totalReduceWaitTime = totalWaitTime;
      runningReduceTasks = runningTaskAttempts;
      neededReduceTasks = numReduceTasks - runningTips - finishedTips
          + neededSpeculativeReduces();
      pendingReduceTasks = numReduceTasks - runningTaskAttempts
          - failedReduceTIPs - finishedReduceTasks + speculativeReduceTasks;
    }
  }
594457
def progress_report(self, force=False):
        '''
        
        '''
        now = datetime.datetime.now()
        if (len(self.task_stack) > 1 or self.task_stack[0] > 0) and \
                now - self.last_report < self.resolution and not force:
            return

        stack_printout = ', '.join('%s %s of %s' % (t.name, t.progress, t.size)
                                   for t in self.task_stack)

        frac_done = self.fraction_done()
        if frac_done == 0.0:
            now_str = now.strftime('%c')
            eta_str = 'unknown on %s' % now_str
        else:
            elapsed = (now - self.start_time)
            estimated_length = elapsed.total_seconds() / frac_done
            eta = self.start_time + datetime.timedelta(seconds=estimated_length)
            eta_str = eta.strftime('%c')

        print '%s (~%d%% done, ETA %s)' % (stack_printout,
                                           round(frac_done * 100.0),
                                           eta_str)
        self.last_report = datetime.datetime.now()
924622
private long getDuration(Set<ITestResult> results)
    {
        long duration = 0;
        for (ITestResult result : results)
        {
            duration += (result.getEndMillis() - result.getStartMillis());
        }
        return duration;
    }
669326
public synchronized void duration(long pause, Context ctxt,
			ILexLocation location)
	{
		// Wait until pause has passed - called by thread

		if (!inOuterTimeStep)
		{
			setTimestep(pause);
			durationEnd = SystemClock.getWallTime() + pause;

			do
			{
				if (Properties.diags_timestep)
				{
					RTLogger.log(new RTExtendedTextMessage(String.format("-- %s Waiting to move time by %d", this, timestep)));
				}

				waitUntilState(RunState.TIMESTEP, RunState.RUNNING, ctxt, location);
				setTimestep(durationEnd - SystemClock.getWallTime());
			} while (getTimestep() > 0);

			setTimestep(Long.MAX_VALUE); // Finished
		}
	}
361585
def end_timing(self, name, elapsed):
        
        counter = self.get(name, CounterType.Interval)
        self._calculate_stats(counter, elapsed)
        self._update()
593942
def maybe_run_for_org(org, task_func, task_key, lock_timeout):
    
    r = get_redis_connection()

    key = TaskState.get_lock_key(org, task_key)

    if r.get(key):
        logger.warning("Skipping task %s for org #%d as it is still running" % (task_key, org.id))
    else:
        with r.lock(key, timeout=lock_timeout):
            state = org.get_task_state(task_key)
            if state.is_disabled:
                logger.info("Skipping task %s for org #%d as is marked disabled" % (task_key, org.id))
                return

            logger.info("Started task %s for org #%d..." % (task_key, org.id))

            prev_started_on = state.last_successfully_started_on
            this_started_on = timezone.now()

            state.started_on = this_started_on
            state.ended_on = None
            state.save(update_fields=("started_on", "ended_on"))

            num_task_args = len(inspect.getargspec(task_func).args)

            try:
                if num_task_args == 3:
                    results = task_func(org, prev_started_on, this_started_on)
                elif num_task_args == 1:
                    results = task_func(org)
                else:
                    raise ValueError("Task signature must be foo(org) or foo(org, since, until)")  # pragma: no cover

                state.ended_on = timezone.now()
                state.last_successfully_started_on = this_started_on
                state.last_results = json.dumps(results)
                state.is_failing = False
                state.save(update_fields=("ended_on", "last_successfully_started_on", "last_results", "is_failing"))

                logger.info("Finished task %s for org #%d with result: %s" % (task_key, org.id, json.dumps(results)))

            except Exception as e:
                state.ended_on = timezone.now()
                state.last_results = None
                state.is_failing = True
                state.save(update_fields=("ended_on", "last_results", "is_failing"))

                logger.exception("Task %s for org #%d failed" % (task_key, org.id))
                raise e
447993
def duration(self):
        
        if self.completion_ts:
            end = self.completed
        else:
            end = datetime.utcnow()
        return end - self.started
952390
void afterCompletion(Task task) {
        boolean delayable = schedule(task);
        DrainStatus status = drainStatus.get();
        if (status.shouldDrainBuffers(delayable)) {
            tryToDrainBuffers();
        }
        notifyListener();
    }
939708
def _calculate_duration(start_time, finish_time):
    """"""
    if not (start_time and finish_time):
        return 0
    start = datetime.datetime.fromtimestamp(start_time)
    finish = datetime.datetime.fromtimestamp(finish_time)
    duration = finish - start

    decimals = float(("0." + str(duration.microseconds)))
    return duration.seconds + decimals