This function is used to indicate that any long running cron processes should exit at the
next opportunity and restart. This is because something (e.g. DB changes) has changed and
the static caches may be stale.
336308
public static function clear_static_caches() {
        global $DB;
        // Do not use get/set config here because the caches cannot be relied on.
        $record = $DB->get_record('config', array('name'=>'scheduledtaskreset'));
        if ($record) {
            $record->value = time();
            $DB->update_record('config', $record);
        } else {
            $record = new \stdClass();
            $record->name = 'scheduledtaskreset';
            $record->value = time();
            $DB->insert_record('config', $record);
        }
    }
578986
public function cron() {
        global $CFG, $DB;
        require_once($CFG->libdir.'/cronlib.php');

        // find out all stale draft areas (older than 4 days) and purge them
        // those are identified by time stamp of the /. root dir
        mtrace('Deleting old draft files... ', '');
        cron_trace_time_and_memory();
        $old = time() - 60*60*24*4;
        $sql = "SELECT *
                  FROM {files}
                 WHERE component = 'user' AND filearea = 'draft' AND filepath = '/' AND filename = '.'
                       AND timecreated < :old";
        $rs = $DB->get_recordset_sql($sql, array('old'=>$old));
        foreach ($rs as $dir) {
            $this->delete_area_files($dir->contextid, $dir->component, $dir->filearea, $dir->itemid);
        }
        $rs->close();
        mtrace('done.');

        // remove orphaned preview files (that is files in the core preview filearea without
        // the existing original file)
        mtrace('Deleting orphaned preview files... ', '');
        cron_trace_time_and_memory();
        $sql = "SELECT p.*
                  FROM {files} p
             LEFT JOIN {files} o ON (p.filename = o.contenthash)
                 WHERE p.contextid = ? AND p.component = 'core' AND p.filearea = 'preview' AND p.itemid = 0
                       AND o.id IS NULL";
        $syscontext = context_system::instance();
        $rs = $DB->get_recordset_sql($sql, array($syscontext->id));
        foreach ($rs as $orphan) {
            $file = $this->get_file_instance($orphan);
            if (!$file->is_directory()) {
                $file->delete();
            }
        }
        $rs->close();
        mtrace('done.');

        // Remove orphaned converted files (that is files in the core documentconversion filearea without
        // the existing original file).
        mtrace('Deleting orphaned document conversion files... ', '');
        cron_trace_time_and_memory();
        $sql = "SELECT p.*
                  FROM {files} p
             LEFT JOIN {files} o ON (p.filename = o.contenthash)
                 WHERE p.contextid = ? AND p.component = 'core' AND p.filearea = 'documentconversion' AND p.itemid = 0
                       AND o.id IS NULL";
        $syscontext = context_system::instance();
        $rs = $DB->get_recordset_sql($sql, array($syscontext->id));
        foreach ($rs as $orphan) {
            $file = $this->get_file_instance($orphan);
            if (!$file->is_directory()) {
                $file->delete();
            }
        }
        $rs->close();
        mtrace('done.');

        // remove trash pool files once a day
        // if you want to disable purging of trash put $CFG->fileslastcleanup=time(); into config.php
        if (empty($CFG->fileslastcleanup) or $CFG->fileslastcleanup < time() - 60*60*24) {
            require_once($CFG->libdir.'/filelib.php');
            // Delete files that are associated with a context that no longer exists.
            mtrace('Cleaning up files from deleted contexts... ', '');
            cron_trace_time_and_memory();
            $sql = "SELECT DISTINCT f.contextid
                    FROM {files} f
                    LEFT OUTER JOIN {context} c ON f.contextid = c.id
                    WHERE c.id IS NULL";
            $rs = $DB->get_recordset_sql($sql);
            if ($rs->valid()) {
                $fs = get_file_storage();
                foreach ($rs as $ctx) {
                    $fs->delete_area_files($ctx->contextid);
                }
            }
            $rs->close();
            mtrace('done.');

            mtrace('Call filesystem cron tasks.', '');
            cron_trace_time_and_memory();
            $this->filesystem->cron();
            mtrace('done.');
        }
    }
394371
def UpdateCronJob(self,
                    cronjob_id,
                    last_run_status=db.Database.unchanged,
                    last_run_time=db.Database.unchanged,
                    current_run_id=db.Database.unchanged,
                    state=db.Database.unchanged,
                    forced_run_requested=db.Database.unchanged):
    """"""
    job = self.cronjobs.get(cronjob_id)
    if job is None:
      raise db.UnknownCronJobError("Cron job %s not known." % cronjob_id)

    if last_run_status != db.Database.unchanged:
      job.last_run_status = last_run_status
    if last_run_time != db.Database.unchanged:
      job.last_run_time = last_run_time
    if current_run_id != db.Database.unchanged:
      job.current_run_id = current_run_id
    if state != db.Database.unchanged:
      job.state = state
    if forced_run_requested != db.Database.unchanged:
      job.forced_run_requested = forced_run_requested
101508
void checkpoint(boolean defrag) {

        if (filesReadOnly) {
            return;
        }

        database.logger.appLog.logContext(SimpleLog.LOG_NORMAL, "start");
        deleteNewAndOldFiles();
        writeScript(false);

        if (cache != null) {
            if (forceDefrag()) {
                defrag = true;
            }

            if (defrag) {
                try {
                    cache.defrag();
                } catch (Exception e) {}
            } else {
                cache.close(true);

                try {
                    cache.backupFile();
                } catch (Exception e1) {
                    deleteNewBackup();
                    cache.open(false);

                    return;
                }

                cache.open(false);
            }
        }

        properties.setDBModified(HsqlDatabaseProperties.FILES_NEW);
        closeLog();
        deleteLog();
        renameNewScript();
        renameNewBackup();
        properties.setDBModified(HsqlDatabaseProperties.FILES_MODIFIED);

        if (dbLogWriter == null) {
            return;
        }

        openLog();

        Session[] sessions = database.sessionManager.getAllSessions();

/*
        try {
            for (int i = 0; i < sessions.length; i++) {
                Session session = sessions[i];

                if (session.isAutoCommit() == false) {
                    dbLogWriter.writeLogStatement(session, session.getAutoCommitStatement());
                }
            }
        } catch (IOException e) {
            throw Error.error(ErrorCode.FILE_IO_ERROR, logFileName);
        }
*/
        database.logger.appLog.logContext(SimpleLog.LOG_NORMAL, "end");
    }
71838
function checkIfNoWorkersAndExit() {
            if (!currentWorkersCount) {
                log('Cluster graceful shutdown: done.');
                if (shutdownTimer) clearTimeout(shutdownTimer);
                exitFunction();
            } else {
                log('Cluster graceful shutdown: wait ' + currentWorkersCount + ' worker' + (currentWorkersCount > 1 ? 's' : '') + '.');
            }
        }
1013012
function CheckpointPlugin () {
    if (!db.getDiskSize) {
      throw new Error(
        'This plugin depends on pouchdb-size plugin. ' +
        'Please add pouchdb-size plugin befor this one.'
      );
    }

    var changes = db.changes({
      live: true,
      since: 'now'
    })
      .on('error', function (error) {
        logger.error(
          'Error while fetching db changes: \'%s\', stack: \'%s\'',
          String(error), error.stack
        );
        changes.cancel();
        db.emit('error', error);
      })
      .on('change', executeOnce(checkDBSize, delay));

    db.on('destroyed', function () {
      destroyed = true;
      changes.cancel();
    });
  }
598805
def monitor(schedule)
      # Parse the cron expression
      cron = CronParser.new(schedule.formatted)

      # Find the time the cron was last expected to run with a 30 second pre buffer
      # and a 30 second post buffer (in addition to the 60 already in place) incase
      # jobs run early/late to allow for clock sync differences between client/hub
      expected_at = cron.last(Time.now.utc) - 30
      expected_by = expected_at + 30 + 60 + 30 # pre buffer + minute wait + post buffer

      # We only need to check jobs that are expected after the monitor start time
      # and jobs that have passed their expected by time and the time the schedule
      # was last updated isn't before when it was expected, i.e we aren't checking for something
      # that should have happened earlier in the day.
      if expected_at > @start_time && Time.now.utc > expected_by && expected_by > schedule.updated_at
        # Check if this execution was created inside a minute window
        # starting when it was expected to run
        check = Minicron::Hub::Model::Execution.exists?(
          created_at: expected_at..expected_by,
          job_id: schedule.job_id
        )

        # If the check failed
        unless check
          Minicron::Alert.send_all(
            user_id: schedule.user_id,
            kind: 'miss',
            schedule_id: schedule.id,
            expected_at: expected_at,
            job_id: schedule.job_id
          )
        end
      end
    end
961388
private int stop(final String[] args) throws IOException {
    setWorkingDir(args);
    final Path statusFile = getStatusPath();
    int exitStatus = 1;

    // determine the current state of the node
    readStatus(false, statusFile);
    if (this.status != null) {
      // upon reading the status file, request the Cache Server to shutdown
      // if it has not already...
      if (this.status.state != Status.SHUTDOWN) {
        // copy server PID and not use own PID; see bug #39707
        this.status = Status.create(this.baseName, Status.SHUTDOWN_PENDING,
            this.status.pid, statusFile);
        this.status.write();
      }

      // poll the Cache Server for a response to our shutdown request
      // (passes through if the Cache Server has already shutdown)
      pollCacheServerForShutdown(statusFile);

      // after polling, determine the status of the Cache Server one last time
      // and determine how to exit...
      if (this.status.state == Status.SHUTDOWN) {
        System.out.println(MessageFormat.format(LAUNCHER_STOPPED,
            this.baseName, getHostNameAndDir()));
        Status.delete(statusFile);
        exitStatus = 0;
      } else {
        System.out.println(MessageFormat.format(LAUNCHER_TIMEOUT_WAITING_FOR_SHUTDOWN,
            this.baseName, this.hostName, this.status));
      }
    } else if (Files.exists(statusFile)) {
      throw new IllegalStateException(MessageFormat.format(
          LAUNCHER_NO_AVAILABLE_STATUS, this.statusName));
    } else {
      System.out.println(MessageFormat.format(LAUNCHER_NO_STATUS_FILE,
          this.workingDir, this.hostName));
    }
    return exitStatus;
  }
953930
def purge_stale_services(argv=None):
    
    argv = argv or sys.argv
    arg_parser = argparse.ArgumentParser(
            prog=os.path.basename(argv[0]), description=(
                'doublethink-purge-stale-services: utility to periodically '
                'purge stale entries from the "services" table.'))

    arg_parser.add_argument(
            "-d", "--rethinkdb-db", required=True, dest="database",
            help="A RethinkDB database containing a 'services' table")

    arg_parser.add_argument("-s", "--rethinkdb-servers",
        metavar="SERVERS", dest="servers", default='localhost',
        help="rethinkdb servers, e.g. db0.foo.org,db0.foo.org:38015,db1.foo.org")

    arg_parser.add_argument(
        '-v', '--verbose', dest='log_level', action='store_const',
        default=logging.INFO, const=logging.DEBUG, help=(
                'verbose logging'))
    args = arg_parser.parse_args(argv[1:])
    logging.basicConfig(
            stream=sys.stdout, level=args.log_level, format=(
                '%(asctime)s %(process)d %(levelname)s %(threadName)s '
                '%(name)s.%(funcName)s(%(filename)s:%(lineno)d) %(message)s'))

    args.servers = [srv.strip() for srv in args.servers.split(",")]

    rethinker = doublethink.Rethinker(servers=args.servers, db=args.database)
    registry = doublethink.services.ServiceRegistry(rethinker)
    registry.purge_stale_services()
    return 0
730154
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
    public void cleanUp() {
        if (theInstance != this && theInstance != null) {
            LOGGER.log(Level.WARNING, "This instance is no longer the singleton, ignoring cleanUp()");
            return;
        }
        synchronized (Jenkins.class) {
            if (cleanUpStarted) {
                LOGGER.log(Level.WARNING, "Jenkins.cleanUp() already started, ignoring repeated cleanUp()");
                return;
            }
            cleanUpStarted = true;
        }
        try {
            LOGGER.log(Level.INFO, "Stopping Jenkins");

            final List<Throwable> errors = new ArrayList<>();

            fireBeforeShutdown(errors);

            _cleanUpRunTerminators(errors);

            terminating = true;

            final Set<Future<?>> pending = _cleanUpDisconnectComputers(errors);

            _cleanUpShutdownUDPBroadcast(errors);

            _cleanUpCloseDNSMulticast(errors);

            _cleanUpInterruptReloadThread(errors);

            _cleanUpShutdownTriggers(errors);

            _cleanUpShutdownTimer(errors);

            _cleanUpShutdownTcpSlaveAgent(errors);

            _cleanUpShutdownPluginManager(errors);

            _cleanUpPersistQueue(errors);

            _cleanUpShutdownThreadPoolForLoad(errors);

            _cleanUpAwaitDisconnects(errors, pending);

            _cleanUpPluginServletFilters(errors);

            _cleanUpReleaseAllLoggers(errors);

            LOGGER.log(Level.INFO, "Jenkins stopped");

            if (!errors.isEmpty()) {
                StringBuilder message = new StringBuilder("Unexpected issues encountered during cleanUp: ");
                Iterator<Throwable> iterator = errors.iterator();
                message.append(iterator.next().getMessage());
                while (iterator.hasNext()) {
                    message.append("; ");
                    message.append(iterator.next().getMessage());
                }
                iterator = errors.iterator();
                RuntimeException exception = new RuntimeException(message.toString(), iterator.next());
                while (iterator.hasNext()) {
                    exception.addSuppressed(iterator.next());
                }
                throw exception;
            }
        } finally {
            theInstance = null;
            if (JenkinsJVM.isJenkinsJVM()) {
                JenkinsJVMAccess._setJenkinsJVM(oldJenkinsJVM);
            }
            ClassFilterImpl.unregister();
        }
    }
892088
def is_old(self):
        
        if not self.processing_started_ts:
            return True

        if self.processing_ended_ts:
            return self.processing_ended_ts + DB_CACHE_TIME < time.time()

        # in case that processing started, but didn't ended in
        # DB_MAX_WAIT_TIME
        expected_end_ts = self.creation_ts + DB_MAX_WAIT_TIME
        if expected_end_ts < time.time():
            logger.error("Prosessing timeouted and properites were not set!")

        return expected_end_ts < time.time()
1281597
public function shutdown()
    {
        foreach ($this->shutdown_functions as $function) {
            call_user_func($function);
        }

        // write session data as soon as possible and before
        // closing database connection, don't do this before
        // registered shutdown functions, they may need the session
        // Note: this will run registered gc handlers (ie. cache gc)
        if ($_SERVER['REMOTE_ADDR'] && is_object($this->session)) {
            $this->session->write_close();
        }

        if (is_object($this->smtp)) {
            $this->smtp->disconnect();
        }

        foreach ($this->caches as $cache) {
            if (is_object($cache)) {
                $cache->close();
            }
        }

        if (is_object($this->storage)) {
            $this->storage->close();
        }

        if ($this->config->get('log_driver') == 'syslog') {
            closelog();
        }
    }
809642
function flushOnChangesQueue() {
      try {
        if (!(--onChangesTtl)) {
          // We have hit the TTL limit so reset everything
          onChangesQueue = undefined;
          throw $compileMinErr('infchng', '{0} $onChanges() iterations reached. Aborting!\n', TTL);
        }
        // We must run this hook in an apply since the $$postDigest runs outside apply
        $rootScope.$apply(function() {
          for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) {
            onChangesQueue[i]();
          }
          // Reset the queue to trigger a new schedule next time there is a change
          onChangesQueue = undefined;
        });
      } finally {
        onChangesTtl++;
      }
    }
1355304
public function calc_cron($cron_string = null)
    {

        if (empty($cron_string)) return false;

        // set the given cronstring
        $this->cron_string = $cron_string;
        // get the curren timestamp
        $this->current_time = strtotime(date('Y-m-d H:i:00', time()));
        $this->calc_time    = strtotime(date('Y-m-d H:i:00', time()));

        $this->next_run      = 0;
        $this->date_next_run = 0;

        // display cleanup
        $this->year        = null;
        $this->cron_month  = null;
        $this->cron_day    = null;
        $this->cron_minute = null;
        $this->cron_hour   = null;

        $count = count($tmp_array = explode(' ', $this->cron_string));

        if (trim($this->cron_string) == '* * * * *' || trim($this->cron_string) == '* * * * * *') {
            $this->next_run      = strtotime('+1 minute', $this->current_time);
            $this->date_next_run = date('Y-m-d H:i:s', $this->next_run);

            // display cleanup
            $this->cron_minute = (strlen($this->cron_minute = date('i', $this->current_time)) < 2) ? "0$this->cron_minute" : $this->cron_minute;
            $this->cron_hour   = (strlen($this->cron_hour = date('h', $this->current_time)) < 2) ? "0$this->cron_hour" : $this->cron_hour;
            $this->cron_day    = (strlen($this->cron_day = date('d', $this->current_time)) < 2) ? "0$this->cron_day" : $this->cron_day;
            $this->cron_month  = (strlen($this->cron_month = date('m', $this->current_time)) < 2) ? "0$this->cron_month" : $this->cron_month;
            $this->cron_year   = (strlen($this->cron_year = date('Y', $this->current_time)) < 2) ? "0$this->cron_hour" : $this->cron_hour;
            $this->cron_array  = array();

            return true;
        }

        // set the cron array
        $this->cron_array = array(
            0 => array(
                'placeholder' => 'i',
                'range'       => array(
                    'range'    => '*',
                    'interval' => false
                ),
                'p_name'      => 'cron_minute'
            ),
            1 => array(
                'placeholder' => 'H',
                'range'       => array(
                    'range'    => '*',
                    'interval' => false
                ),
                'p_name'      => 'cron_hour'
            ),
            2 => array(
                'placeholder' => 'd',
                'range'       => array(
                    'range'    => '*',
                    'interval' => false
                ),
                'p_name'      => 'cron_day'
            ),
            3 => array(
                'placeholder' => 'm',
                'range'       => array(
                    'range'    => '*',
                    'interval' => false
                ),
                'p_name'      => 'cron_month'
            ),
            4 => array(
                'placeholder' => 'w',
                'range'       => array(
                    'range'    => '*',
                    'interval' => false
                ),
                'p_name'      => 'cron_weekday'
            ),
            5 => array(
                'placeholder' => 'Y',
                'range'       => array(
                    'range'    => '*',
                    'interval' => false
                ),
                'p_name'      => 'cron_year'
            )
        );

        // get the time range for the specific year / month
        for ($i = 0; $i < $count; $i++) {
            $this->cron_array[$i]['range'] = $this->parse_position($tmp_array[$i]);
        }

        unset($tmp_array, $i);

        // since the year is optional
        if ($count < 6) {
            $this->cron_array[5]['range'] = $this->parse_position(date('Y'));
            $count++;
        }

        $next_up = false;

        // foreach ( $this->cron_array as $key => $val )
        for ($i = 0; $i < $count; $i++) {
            if (!empty($this->cron_array[$i]['range']) && !is_array($this->cron_array[$i]['range']['range'])) {
                $sub_range = array(
                    'range'       => $this->cron_array[$i]['range']['range'],
                    'interval'    => $this->cron_array[$i]['range']['interval'],
                    'placeholder' => $this->cron_array[$i]['placeholder'],
                    'p_name'      => $this->cron_array[$i]['p_name']
                );

                $this->__set_value($sub_range);
            } else {

                foreach ($this->cron_array[$i]['range'] as $range) {
                    if (!is_array($range)) continue;

                    if ($next_up === true) {
                        $val_string  = (string)substr($this->cron_array[$i]['p_name'], 5);
                        $val         = (string)date($this->cron_array[$i]['placeholder'], strtotime("+1 $val_string", $this->calc_time));
                        $date_string = '';
                        switch ($i) {
                            case 0 :
                                $date_string = (string)"Y-m-d H:$val:00";
                                break;
                            case 1 :
                                $date_string = (string)"Y-m-d $val:00:00";
                                break;
                            case 2 :
                                $date_string = (string)"Y-m-$val 00:00:00";
                                break;
                            case 3 :
                                $date_string = (string)"Y-$val-01 00:00:00";
                                break;
                            case 4 :
                                break;
                            case 5 :
                                $date_string = (string)"$val-01-01 00:00";
                                break;
                            default :
                                $date_string = (string)"Y-m-d H:i:s";
                                break;
                        }
                        // the calcuation date
                        $this->calc_time = (int)strtotime(date((string)$date_string));

                        // reset the restart
                        $next_up = false;

                        for ($x = 0; count($this->cron_array) > $x; $x++) {
                            $this->{$this->cron_array[$x]['p_name']} = null;
                        }
                        // cleanup useless vars
                        unset($x, $val, $val_string, $date_string);
                        // reset to the first field
                        $i = -1;
                        // start from beginning break this loop
                        break;
                    }

                    // go through all subranges
                    foreach ($range as $sub_range) {
                        $sub_range['placeholder'] = (string)$this->cron_array[$i]['placeholder'];
                        $sub_range['p_name']      = (string)$this->cron_array[$i]['p_name'];
                        if (!empty($this->{$this->cron_array[$i]['p_name']})) break;
                        $this->__set_value((array)$sub_range);
                    }

                    // check if a value has been set
                    if (!isset($this->{$this->cron_array[$i]['p_name']})) {
                        $next_up = true;
                    }
                    unset($sub_range);
                }
                unset($range);
            }
        }
        // display cleanup
        $this->cron_minute = (strlen($this->cron_minute) < 2) ? "0$this->cron_minute" : $this->cron_minute;
        $this->cron_hour   = (strlen($this->cron_hour) < 2) ? "0$this->cron_hour" : $this->cron_hour;
        $this->cron_day    = (strlen($this->cron_day) < 2) ? "0$this->cron_day" : $this->cron_day;
        $this->cron_month  = (strlen($this->cron_month) < 2) ? "0$this->cron_month" : $this->cron_month;
        // set the next possible timestamp
        $this->date_next_run = "{$this->cron_year}-{$this->cron_month}-{$this->cron_day} {$this->cron_hour}:{$this->cron_minute}:00";
        $this->next_run      = strtotime($this->date_next_run);

        // clear cron array
        $this->cron_array = array();

        return $this->next_run;
    }
573477
def cleanup(self):
        
        now = time.time()
        expired = now - NODE_TIMEOUT
        if self.conn.zremrangebyscore(self.key, 0, expired):
            self._notify()
700239
function restart() {
	logger.log('Restarting', clc.green(script));
	notifyWebSocket('restart');
	if (!kill(true)) {
		// The process wasn't running, start it now.
		start(true);
	} /*else {
		// The process will restart when its 'exit' event is emitted.
	}*/
}
985071
function until($func,$args=NULL,$timeout=60) {
		if (!$args)
			$args=[];
		$time=time();
		$max=ini_get('max_execution_time');
		$limit=max(0,($max?min($timeout,$max):$timeout)-1);
		$out='';
		// Turn output buffering on
		ob_start();
		// Not for the weak of heart
		while (
			// No error occurred
			!$this->hive['ERROR'] &&
			// Got time left?
			time()-$time+1<$limit &&
			// Still alive?
			!connection_aborted() &&
			// Restart session
			!headers_sent() &&
			(session_status()==PHP_SESSION_ACTIVE || session_start()) &&
			// CAUTION: Callback will kill host if it never becomes truthy!
			!$out=$this->call($func,$args)) {
			if (!$this->hive['CLI'])
				session_commit();
			// Hush down
			sleep(1);
		}
		ob_flush();
		flush();
		return $out;
	}