Terminates a cronjob-run if it has exceeded its maximum runtime.

    This is a no-op for cronjobs that allow overruns.

    Raises:
      LifetimeExceededError: If the cronjob has exceeded its maximum runtime.
498944
def HeartBeat(self):
    
    # In prod, self.job.lifetime is guaranteed to always be set, and is
    # always equal to self.__class__.lifetime. Some tests however, do not
    # set the job lifetime, which isn't great.
    if self.allow_overruns or not self.job.lifetime:
      return

    runtime = rdfvalue.RDFDatetime.Now() - self.run_state.started_at
    if runtime > self.lifetime:
      raise LifetimeExceededError(
          "Cronjob run has exceeded the maximum runtime of %s." % self.lifetime)
38462
def abort(self, msg=None):
        '''
        '''
        if not self.abort_run.is_set():
            if msg:
                logging.error('%s%s Aborting run...', msg, ('' if msg[-1] in punctuation else '.'))
            else:
                logging.error('Aborting run...')
        self.abort_run.set()
        self.stop_run.set()
384080
def terminate(self):
        

        self.info_log('The test batch is finished.')

        with DbSessionContext(BROME_CONFIG['database']['mongo_database_name']) as session:  # noqa
            test_batch = session.query(Testbatch)\
                .filter(Testbatch.mongo_id == self.test_batch_id).one()
            test_batch.ending_timestamp = utcnow()
            test_batch.terminated = True
            session.save(test_batch, safe=True)

        self.print_test_summary(self.executed_tests)
562401
def terminate(self):
        
        self.handle, handle = None, self.handle
        if threading.current_thread() is self._event_thread:
            # Handle special case to allow event handle to be detached.
            # This is necessary since otherwise the event thread would deadlock itself.
            grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle))
            grim_reaper.start()
        else:
            _mpv_terminate_destroy(handle)
            if self._event_thread:
                self._event_thread.join()
308936
def stop(self):
        
        if self._start_instant is None:
            raise IntervalException("Attempt to stop an interval that has not started.")
        if self._stop_instant is None:
            self._stop_instant = instant()
            self._duration = int((self._stop_instant - self._start_instant) * 1000)
            return self._duration
        return False
89936
def _declareTimeoutExceeded(self, ev_data: RestartLogData):
        
        logger.info("Timeout exceeded for {}".format(ev_data.when))
        last = self._actionLog.last_event
        if (last and last.ev_type == RestartLog.Events.failed and
                last.data == ev_data):
            return None

        self._action_failed(ev_data,
                            reason="exceeded restart timeout")

        self._unscheduleAction()
        self._actionFailedCallback()
1198396
def _run_done_callbacks(self):
        ''' 
        '''
        with self._callbacks_lock:
            for callback in self._done_callbacks:
                try:
                    callback()
                # We do not want a callback interrupting the process, especially
                # in the failure cleanups. So log and catch, the excpetion.
                except Exception as ex:
                    logger.error("Exception: %s" % str(ex))
                    logger.error("Exception raised in %s." % callback, exc_info=True)

            self._done_callbacks = []
740616
def _IsCronJobFailing(self, cron_job):
    """"""
    status = cron_job.Get(cron_job.Schema.LAST_RUN_STATUS)
    if status is None:
      return False

    return status.status != rdf_cronjobs.CronJobRunStatus.Status.OK
907433
private void runDeferredStop() {
        // Stop current jobs from running.
        clearWaitJobs();
        // Schedule deferred stop executor.
        log.trace("Ran deferred stop");
        if (deferredStop == null) {
            // set deferred stop if we get a job name returned 
            deferredStop = subscriberStream.scheduleWithFixedDelay(new DeferredStopRunnable(), 100);
        }
    }
1334806
def terminate
      raise "Cannot terminate an exclusive task" if exclusive?

      if running?
        # !!! DO NOT INTRODUCE ADDITIONAL GLOBAL VARIABLES !!!
        # rubocop:disable Style/GlobalVars
        if $CELLULOID_DEBUG
          Internals::Logger.with_backtrace(backtrace) do |logger|
            type = @dangerous_suspend ? :warn : :debug
            logger.send(type, "Terminating task: type=#{@type.inspect}, meta=#{@meta.inspect}, status=#{@status.inspect}")
          end
        end
        # rubocop:enable Style/GlobalVars

        exception = TaskTerminated.new("task was terminated")
        exception.set_backtrace(caller)
        resume exception
      else
        raise DeadTaskError, "task is already dead"
      end
    end
484797
protected OptionalThing<RunnerResult> stopConcurrentJobIfNeeds(Cron4jJob job) { // in preparing lock
        synchronized (runningState) {
            final OptionalThing<RunnerResult> concurrentResult = createConcurrentJobStopper().stopIfNeeds(job, () -> {
                return runningState.getBeginTime().get().toString(); // locked so can get safely
            });
            if (concurrentResult.isPresent()) {
                return concurrentResult;
            }
            // will wait for previous job by synchronization later
        }
        return OptionalThing.empty();
    }
273611
def cap_runs!
      runs_count = self.runs.count
      if runs_count > max_run_per_job
        runs.sort_by(:started_at, order: 'ALPHA ASC', limit: [0, runs_count - max_run_per_job]).each do |run|
          if run.status == :failed || run.status == :success
            run.delete
          end
        end
      end
    end
934051
def __run(self):
		
		self.interval_start = time.time()
		while self.status != STOPPED:
			if self.status == RUNNING:
				self.current_interval_duration = time.time() - self.interval_start

			# If max_duration is set, stop the clock if it is reached
			if self.max_duration and self.time > self.max_duration:
				self.status == STOPPED

			# One refresh per millisecond seems enough
			time.sleep(0.001)
1079803
def stop
      if(@runner.nil? && @stop)
        raise NotRunning.new
      elsif(@runner.nil? || !@runner.alive?)
        @stop = true
        @runner = nil
      else
        @stop = true
        if(@runner)
          @runner.raise Resync.new if @runner.alive? && @runner.stop?
          @runner.join(0.05) if @runner
          @runner.kill if @runner && @runner.alive?
        end
        @runner = nil
      end
      nil
    end
1229597
private void tryRunNext() {
        while (runningSemaphore.tryAcquire()) {
            ExecutionTask execution = queue.poll();
            if (execution != null) {
                // Note: we've removed the execution from the queue so we're committed to running it
                // if we fail to do so for any reason, we need to call the exception handler to fail the execution
                try {
                    execution.submit();
                } catch (Throwable e) {
                    // Any exception here is unexpected
                    runningSemaphore.release();
                    execution.exceptionHandler.handle(e);
                }
            } else {
                runningSemaphore.release();
                break;
            }
        }
    }
800477
def _end_flusher_loop(self):
        
        if not self.is_connected or self.is_connecting or self.io.closed():
            if self._flush_queue is not None and self._flush_queue.empty():
                self._flush_pending(check_connected=False)
            yield tornado.gen.moment
181761
def reissueOverLongJobs(self):
        
        maxJobDuration = self.config.maxJobDuration
        jobsToKill = []
        if maxJobDuration < 10000000:  # We won't bother doing anything if rescue time > 16 weeks.
            runningJobs = self.batchSystem.getRunningBatchJobIDs()
            for jobBatchSystemID in list(runningJobs.keys()):
                if runningJobs[jobBatchSystemID] > maxJobDuration:
                    logger.warn("The job: %s has been running for: %s seconds, more than the "
                                "max job duration: %s, we'll kill it",
                                str(self.jobBatchSystemIDToIssuedJob[jobBatchSystemID].jobStoreID),
                                str(runningJobs[jobBatchSystemID]),
                                str(maxJobDuration))
                    jobsToKill.append(jobBatchSystemID)
            self.killJobs(jobsToKill)