Manage the task to handle restarts, reconfiguration, etc.

        Returns True to request a shorter period before the next call,
        False if nothing special is needed.
503964
def manage(self):
        
        log = self._params.get('log', self._discard)
        if self._stopping:
            log.debug("Task '%s', stopping, retrying stop()", self._name)
            return self.stop()
        now = time.time()
        if self._started and self._limit:
            if now > self._limit:
                log.debug("Task '%s', time limit exceeded by %s, stopping", self._name, deltafmt(now - self._limit))
                return self.stop()
            else:
                log.debug("Task '%s', time limit remaining %s", self._name, deltafmt(self._limit - now))
        if self._legion.is_exiting():
            log.debug("Not managing '%s', legion is exiting", self._name)
            return False
        log.debug("managing '%s'", self._name)
        return self._start()
826111
def xmlrpc_reschedule(self):
        
        if not len(self.scheduled_tasks) == 0:
            self.reschedule = list(self.scheduled_tasks.items())
            self.scheduled_tasks = {}
        return True
1024745
@Override
    boolean tryObtainPermission() {
        // Thread-safe
        if (clock.instant().isAfter(retryAfterWaitDuration)) {
            stateMachine.transitionToHalfOpenState();
            return true;
        }
        circuitBreakerMetrics.onCallNotPermitted();
        return false;
    }
764259
function () {
    var self = this;
    if (self._pollsScheduledButNotStarted > 0)
      return;
    ++self._pollsScheduledButNotStarted;
    self._taskQueue.queueTask(function () {
      self._pollMongo();
    });
  }
150118
def handle_next_request(self):
        
        if not self._idle_timer:
            # This method may be called multiple times before receiving a request, so we only create and start a timer
            # if it's the first call or if the idle timer was stopped on the last call.
            self._idle_timer = self.metrics.timer('server.idle_time', resolution=TimerResolution.MICROSECONDS)
            self._idle_timer.start()

        # Get the next JobRequest
        try:
            request_id, meta, job_request = self.transport.receive_request_message()
        except MessageReceiveTimeout:
            # no new message, nothing to do
            self.perform_idle_actions()
            return

        # We are no longer idle, so stop the timer and reset for the next idle period
        self._idle_timer.stop()
        self._idle_timer = None

        try:
            PySOALogContextFilter.set_logging_request_context(request_id=request_id, **job_request.get('context', {}))
        except TypeError:
            # Non unicode keys in job_request['context'] will break keywording of a function call.
            # Try to recover by coercing the keys
            PySOALogContextFilter.set_logging_request_context(
                request_id=request_id,
                **{six.text_type(k): v for k, v in six.iteritems(job_request['context'])}
            )

        request_for_logging = self.logging_dict_wrapper_class(job_request)
        self.job_logger.log(self.request_log_success_level, 'Job request: %s', request_for_logging)

        try:
            self.perform_pre_request_actions()

            # Process and run the Job
            job_response = self.process_job(job_request)

            # Prepare the JobResponse for sending by converting it to a message dict
            try:
                response_message = attr.asdict(job_response, dict_factory=UnicodeKeysDict)
            except Exception as e:
                self.metrics.counter('server.error.response_conversion_failure').increment()
                job_response = self.handle_job_exception(e, variables={'job_response': job_response})
                response_message = attr.asdict(job_response, dict_factory=UnicodeKeysDict)

            response_for_logging = self.logging_dict_wrapper_class(response_message)

            # Send the response message
            try:
                if not job_request.get('control', {}).get('suppress_response', False):
                    self.transport.send_response_message(request_id, meta, response_message)
            except MessageTooLarge as e:
                self.metrics.counter('server.error.response_too_large').increment()
                job_response = self.handle_job_error_code(
                    ERROR_CODE_RESPONSE_TOO_LARGE,
                    'Could not send the response because it was too large',
                    request_for_logging,
                    response_for_logging,
                    extra={'serialized_length_in_bytes': e.message_size_in_bytes},
                )
                self.transport.send_response_message(
                    request_id,
                    meta,
                    attr.asdict(job_response, dict_factory=UnicodeKeysDict),
                )
            except InvalidField:
                self.metrics.counter('server.error.response_not_serializable').increment()
                job_response = self.handle_job_error_code(
                    ERROR_CODE_RESPONSE_NOT_SERIALIZABLE,
                    'Could not send the response because it failed to serialize',
                    request_for_logging,
                    response_for_logging,
                )
                self.transport.send_response_message(
                    request_id,
                    meta,
                    attr.asdict(job_response, dict_factory=UnicodeKeysDict),
                )
            finally:
                if job_response.errors or any(a.errors for a in job_response.actions):
                    if (
                        self.request_log_error_level > self.request_log_success_level and
                        self.job_logger.getEffectiveLevel() > self.request_log_success_level
                    ):
                        # When we originally logged the request, it may have been hidden because the effective logging
                        # level threshold was greater than the level at which we logged the request. So re-log the
                        # request at the error level, if set higher.
                        self.job_logger.log(self.request_log_error_level, 'Job request: %s', request_for_logging)
                    self.job_logger.log(self.request_log_error_level, 'Job response: %s', response_for_logging)
                else:
                    self.job_logger.log(self.request_log_success_level, 'Job response: %s', response_for_logging)
        finally:
            PySOALogContextFilter.clear_logging_request_context()
            self.perform_post_request_actions()
496093
def set_settings!(new_settings, options = {}, request_options = {})
      res = set_settings(new_settings, options, request_options)
      wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
      res
    end
24489
def ensure_started(self):
        
        # server is either starting or stopping (or error)
        if self.state in ['maintenance', 'error']:
            self._wait_for_state_change(['stopped', 'started'])

        if self.state == 'stopped':
            self.start()
            self._wait_for_state_change(['started'])

        if self.state == 'started':
            return True
        else:
            # something went wrong, fail explicitly
            raise Exception('unknown server state: ' + self.state)
551417
private void reConfigureAsynchronously() {
        refreshCount.incrementAndGet();
        if (pendingRefreshes.incrementAndGet() == 1) {
            executorPool.submit(new Runnable() {
                @Override
                public void run() {
                    do {
                        try {
                            Thread.sleep(MIN_DELAY_BETWEEN_REFRESHES);
                            logger.info("Configuring log4j dynamically");
                            reconfigure();
                        } 
                        catch (Exception th) {
                            logger.error("Cannot dynamically configure log4j :", th);
                        }
                    } while (0 != pendingRefreshes.getAndSet(0));
                }
            });
        }
    }
1345563
function() {
        // Important to configure later to not use UTC.
        later.date.localTime();

        // Shutdown on schedule.
        if (this.get('shutdownSchedule')) {
            this._shutdownSchedule = later.parse.cron(this.get('shutdownSchedule'));
            if (this._shutdownInterval) {
                this._shutdownInterval.clear();
            }

            this._shutdownInterval = later.setInterval(_.bind(function() {
                logger.info('App shutdown time has arrived. ' + new Date());
                this.set('restartCount', 0);
                this.shutdownApp();
            }, this), this._shutdownSchedule);
        }

        // Shutdown on schedule.
        if (this.get('shutdownPcSchedule')) {
            this._shutdownPcSchedule = later.parse.cron(this.get('shutdownPcSchedule'));
            if (this._shutdownPcInterval) {
                this._shutdownPcInterval.clear();
            }

            this._shutdownPcInterval = later.setInterval(_.bind(function() {
                logger.info('Machine shutdown time has arrived. ' + new Date());
                this.set('restartCount', 0);
                this.shutdownMachine();
            }, this), this._shutdownPcSchedule);
        }

        // Start up on schedule.
        if (this.get('startupSchedule')) {
            this._startupSchedule = later.parse.cron(this.get('startupSchedule'));
            if (this._startupInterval) {
                this._startupInterval.clear();
            }

            this._startupInterval = later.setInterval(_.bind(function() {
                logger.info('App startup time has arrived. ' + new Date());
                if (!$$serverState.get('runApp')) {
                    logger.info('Startup disabled by console.');
                    return;
                }

                this.set('restartCount', 0);
                this.startApp();
            }, this), this._startupSchedule);
        }

        // Start up on schedule.
        if (this.get('restartSchedule')) {
            this._restartSchedule = later.parse.cron(this.get('restartSchedule'));
            if (this._restartInterval) {
                this._restartInterval.clear();
            }

            this._restartInterval = later.setInterval(_.bind(function() {
                if (this._isStartingUp || this._isShuttingDown) {
                    return;
                }

                logger.info('App restart time has arrived. ' + new Date());
                if (!$$serverState.get('runApp')) {
                    logger.info('Startup disabled by console.');
                    return;
                }

                this.set('restartCount', 0);
                this.restartApp();
            }, this), this._restartSchedule);
        }

        // Restart machine on schedule.
        if (this.get('restartPcSchedule')) {
            this._restartPcSchedule = later.parse.cron(this.get('restartPcSchedule'));
            if (this._restartPcInterval) {
                this._restartPcInterval.clear();
            }

            this._restartPcInterval = later.setInterval(_.bind(function() {
                logger.info('Machine restart time has arrived. ' + new Date());

                this.restartMachine();

            }, this), this._restartPcSchedule);
        }

    }
1008405
private boolean tryToNotifyReset() {
        if ((mStatus == PTR_STATUS_COMPLETE || mStatus == PTR_STATUS_PREPARE) && mPtrIndicator.isInStartPosition()) {
            if (mPtrUIHandlerHolder.hasHandler()) {
                mPtrUIHandlerHolder.onUIReset(this);
                if (DEBUG) {
                    PtrCLog.i(LOG_TAG, "PtrUIHandler: onUIReset");
                }
            }
            mStatus = PTR_STATUS_INIT;
            clearFlag();
            return true;
        }
        return false;
    }
486186
private Runnable decorateTask(Runnable task, boolean isRepeatingTask) {
        Runnable result = TaskUtils.decorateTaskWithErrorHandler(task, this.errorHandler, isRepeatingTask);
        if (this.enterpriseConcurrentScheduler) {
            result = ManagedTaskBuilder.buildManagedTask(result, task.toString());
        }
        return result;
    }
117090
def trigger(self):
        ''''''
        tnow = time.time()

        if tnow < self.last_time:
            print("Warning, time moved backwards. Restarting timer.")
            self.last_time = tnow

        if self.last_time + (1.0/self.frequency) <= tnow:
            self.last_time = tnow
            return True
        return False
1216331
synchronized void scheduleRetry(long retryInterval)
    {
        // Synchronized to insure a destroyed or cancelled (ivTaskHanler=null)
        // timer is not re-scheduled. If the timer is in the cancelled state
        // but not yet destroyed, then reset the expiration back to the last
        // expiration since it was never completed successfully. If the cancel
        // does rollback then schedule will be called again and re-create the
        // task handler. The only side effect of this is that the retry count
        // is reset; so the timer may experience more retries than configured. RTC107334

        if (!ivDestroyed)
        {
            if (ivTaskHandler != null)
            {
                ivTaskHandler.scheduleRetry(retryInterval);
            }
            else
            {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    Tr.debug(tc, "scheduleRetry: not scheduled, timer in cancelled state : " + ivTaskId);
                ivExpiration = ivLastExpiration;
            }
        }
    }
1065582
public boolean isRestartScheduled() {
        for (UpdateCenterJob job : getJobs()) {
            if (job instanceof RestartJenkinsJob) {
                RestartJenkinsJob.RestartJenkinsJobStatus status = ((RestartJenkinsJob) job).status;
                if (status instanceof RestartJenkinsJob.Pending
                        || status instanceof RestartJenkinsJob.Running) {
                    return true;
                }
            }
        }
        return false;
    }
603657
def _need_update(self):
        ''
        if self.currval >= self.next_update or self.finished: return True

        delta = time.time() - self.last_update_time
        return self._time_sensitive and delta > self.poll
63501
def restart_complete(self, state, new_address):
        '''
        
        '''
        if state.timeout_call_id:
            state.agent.cancel_delayed_call(state.timeout_call_id)
            state.timeout_call_id = None
        return self._send_restarted_notifications(new_address)
13888
private void rescheduleTask(AtomicReference<TimerTask> taskRef, long millis) {
    ProcessorTask newTask = new ProcessorTask();
    timer.schedule(newTask, millis);
    swapAndCancelTask(taskRef, newTask);
  }