This is were the activityMonitor is set up. The monitor will keep check
for the currently active activity.
492529
private void setupActivityMonitor() {
		if(config.trackActivities){
			try {
				IntentFilter filter = null;
				activityMonitor = inst.addMonitor(filter, null, false);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
161081
def ismonitor(self):
        """"""
        if self.cache_mode is not None:
            return self.cache_mode
        try:
            res = (self.mode() == "monitor")
            self.cache_mode = res
            return res
        except Scapy_Exception:
            return False
1130341
public synchronized boolean startMonitor() {
        if (this.executor != null) {
            if (this.monitorHandle == null) {
                this.monitorHandle = this.executor.scheduleWithFixedDelay(this.monitor, this.monitorInterval, this.monitorInterval, TimeUnit.MILLISECONDS);
            }
            return true;
        }
        return false;
    }
1098096
def is_active(self):
        """"""
        if self._queue.exhausted:
            return False
        return any(ch.is_active for ch in self._refs.values())
896608
def is_running(self):
        
        return self.state in [self.STATE_IDLE, self.STATE_ACTIVE,
                              self.STATE_SLEEPING]
1109357
private void processActivity(Activity activity)
   {
      Task task = getParentTask(activity).addTask();
      task.setText(1, activity.getId());

      task.setActualDuration(activity.getActualDuration());
      task.setActualFinish(activity.getActualFinish());
      task.setActualStart(activity.getActualStart());
      //activity.getBaseunit()
      //activity.getBilled()
      //activity.getCalendar()
      //activity.getCostAccount()
      task.setCreateDate(activity.getCreationTime());
      task.setFinish(activity.getCurrentFinish());
      task.setStart(activity.getCurrentStart());
      task.setName(activity.getDescription());
      task.setDuration(activity.getDurationAtCompletion());
      task.setEarlyFinish(activity.getEarlyFinish());
      task.setEarlyStart(activity.getEarlyStart());
      task.setFreeSlack(activity.getFreeFloat());
      task.setLateFinish(activity.getLateFinish());
      task.setLateStart(activity.getLateStart());
      task.setNotes(activity.getNotes());
      task.setBaselineDuration(activity.getOriginalDuration());
      //activity.getPathFloat()
      task.setPhysicalPercentComplete(activity.getPhysicalPercentComplete());
      task.setRemainingDuration(activity.getRemainingDuration());
      task.setCost(activity.getTotalCost());
      task.setTotalSlack(activity.getTotalFloat());
      task.setMilestone(activityIsMilestone(activity));
      //activity.getUserDefined()
      task.setGUID(activity.getUuid());

      if (task.getMilestone())
      {
         if (activityIsStartMilestone(activity))
         {
            task.setFinish(task.getStart());
         }
         else
         {
            task.setStart(task.getFinish());
         }
      }

      if (task.getActualStart() == null)
      {
         task.setPercentageComplete(Integer.valueOf(0));
      }
      else
      {
         if (task.getActualFinish() != null)
         {
            task.setPercentageComplete(Integer.valueOf(100));
         }
         else
         {
            Duration remaining = activity.getRemainingDuration();
            Duration total = activity.getDurationAtCompletion();
            if (remaining != null && total != null && total.getDuration() != 0)
            {
               double percentComplete = ((total.getDuration() - remaining.getDuration()) * 100.0) / total.getDuration();
               task.setPercentageComplete(Double.valueOf(percentComplete));
            }
         }
      }

      m_activityMap.put(activity.getId(), task);
   }
1135380
public void startWatching() {
        try {
            final List<MonitorLine> lines = getSource().getLastLine(getInitialCount());
            actual = null;
            updateLines(lines);
        } catch (Exception e) {
            notifyObservers(e);
        }
    }
762906
public synchronized void onTransportActive() {
    if (state == State.IDLE) {
      // When the transport goes active, we do not reset the nextKeepaliveTime. This allows us to
      // quickly check whether the connection is still working.
      state = State.PING_SCHEDULED;
      if (pingFuture == null) {
        pingFuture = scheduler.schedule(
            sendPing,
            keepAliveTimeInNanos - stopwatch.elapsed(TimeUnit.NANOSECONDS),
            TimeUnit.NANOSECONDS);
      }
    } else if (state == State.IDLE_AND_PING_SENT) {
      state = State.PING_SENT;
    } // Other states are possible when keepAliveDuringTransportIdle == true
  }
839757
public void checkUpdate(Activity activity, CheckUpdateHandler handler) {
        HMSAgentLog.i("checkUpdate:handler=" + StrUtils.objDesc(handler));
        this.handler = handler;
        this.activity = activity;
        connect();
    }
400583
function () {
        checkDisposed(this);
        if (this.isStopped) { return; }
        this.isStopped = true;
        var now = this.scheduler.now();
        this._trim(now);
        for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
          var observer = os[i];
          observer.onCompleted();
          observer.ensureActive();
        }
        this.observers.length = 0;
      }
38981
public static void setActive(boolean active) {
    if (active) System.setProperty(ACTIVATE_PROPERTY, "true");
    else System.clearProperty(ACTIVATE_PROPERTY);
    TimerTrace.active = active;
  }
462739
boolean isMonitored(HttpSession session) {
		boolean monitor = false;
		if (null != session && session.getAttribute(Constants.Options.OPTIONS) != null) {
			monitor = ((Options) session.getAttribute(Constants.Options.OPTIONS)).isMonitor();
		}
		return monitor;
	}
1190120
public void raActive() {
		// init client
		client = new XcapClientImpl();		
		activities = new ConcurrentHashMap<XCAPResourceAdaptorActivityHandle, AsyncActivityImpl>();
		executorService = Executors.newCachedThreadPool();
		sbbInterface.setActive(true);
	}
1124568
def is_running(self) -> bool:
        """"""
        return (
            self._has_started and
            self.is_alive() or
            self.completed_at is None or
            (datetime.utcnow() - self.completed_at).total_seconds() < 0.5
        )
915418
def active(self):
        

        task = self._get_task()
        if not task:
            return super(AsyncioScopeManager, self).active

        return self._get_task_scope(task)
144208
@Override
    public void monitor() {
        Runtime runtime = Runtime.getRuntime();

        double allocatedMemory = runtime.totalMemory() / (double) 1024;
        double freeMemory = runtime.freeMemory() / (double) 1024;

        double totalFreeMemory = freeMemory + (maxMemory - allocatedMemory);

        calculatedAllocatedMemory = allocatedMemory;
        calculatedFreeMemory = freeMemory;
        calculatedTotalFreeMemory = totalFreeMemory;

        this.percentageOfMemoryUsed = (((double) 100) - ((totalFreeMemory / maxMemory) * ((double) 100)));

        super.applyNewValue(memoryAlarmLevel, percentageOfMemoryUsed, memoryThreshold, backToNormalMemoryThreshold, true);
    }
1153480
function activitiesMonitoringStep(){
	pipeRunStep.call(this);

	this.label = "Monitoring DataWorks activities for completion";

	//public APIs
	this.run = function( callback ){
		var logger = this.pipeRunStats.logger;
		var pipeRunStats = this.pipeRunStats;

		//Get the DataWorks instance
		var dwInstance = pipeRunStats.dwInstance;

		var stepStats = this.stats;
		stepStats.numRunningActivities = 0;
		_.forOwn( pipeRunStats.getTableStats(), function(value, key ){
			stepStats.numRunningActivities++;
		})

		stepStats.numFinishedActivities = 0;

		//convenience method
		var expectedLength = this.getPipeRunner().getSourceTables().length;
		var formatStepMessage = function(){
			var percent = ((stepStats.numFinishedActivities/expectedLength)*100).toFixed(1);
			this.setPercentCompletion( percent );
			var message = stepStats.numFinishedActivities + " DataWorks activities completed (" + percent + "%)";
			this.setStepMessage( message );
		}.bind(this);

		var sendAlert = function(){
			logger.info("Sending alert about possible DataWorks activities hung to metrics-collector");
			async.forEachOf( pipeRunStats.getTableStats(), function(tableStats, tableName, callback ){
				if ( !tableStats.activityDone ){
					var d = moment();
					var props = {
						idsite: "data.pipes",
						type : "pipe_alert",
						activityId: tableStats.activityId,
						activityRunId: tableStats.activityRunId,
						tableName: tableStats.tableName,
						numRecords: tableStats.numRecords,
						date: d.year() + "-" + (d.month() + 1) + "-" + d.date(),
						d: d.format()
					};
					request.get( {url: "http://metrics-collector.mybluemix.net/tracker", qs: props}, function(err, response, body){
						if ( !err ){
							logger.info("Successfully logged an alert to metrics-collector");
						}
						return callback( err );
					});
				}
			},function(err){
				if ( err ){
					logger.error("Unable to create DataWorks activity hung alert: " + err );
				}
			});
		}

		//Start monitoring the activities
		var timeout = moment.duration(5, 'minutes').asMilliseconds();	//timeout to raise possible dataworks hung alerts when no activities has completed.
		var alertSent = false;
		var start = moment();
		formatStepMessage();
		var monitor = function(){
			async.forEachOf( pipeRunStats.getTableStats(), function(tableStats, tableName, callback ){
				if ( !tableStats.activityDone ){
					dwInstance.monitorActivityRun( tableStats.activityId, tableStats.activityRunId, function( err, activityRun ){
						if ( err ){
							return callback(err);
						}
						if ( dwInstance.isFinished( activityRun.status ) ){
							logger.trace("ActivityRun %s complete", tableStats.activityRunId);
							stepStats.numFinishedActivities++;
							stepStats.numRunningActivities--;
							tableStats.activityDone = true;
							formatStepMessage();

							//Reset the timeout start
							start = moment();
						}
						return callback();
					})
				}else{
					return callback();
				}
			},function(err){
				if ( err ){
					return callback(err);
				}
				if ( stepStats.numRunningActivities > 0 ){
					//Schedule another round
					if ( moment.duration( moment().diff(start) ).asMilliseconds() > timeout ){
						if ( !alertSent ){
							alertSent = true;
							sendAlert();
						}
					}
					return setTimeout( monitor, 10000 );
				}
				var message = "DataWorks activities are complete";
				logger.info( message );
				stepStats.status = message;
				this.setStepMessage(message);
				return callback();
			}.bind(this));
		}.bind(this);
		setTimeout( monitor, 10000 );
	}
}