/* Step two, once every few hours, we delete the expired sessions.
777673
function verifyExpiration(initialStart) {
    if (initialStart && global.THORIN_SETUP) return;
    if (opt.removeExpired === false) return;
    let now = new Date(),
      Session = storeObj.model(modelName);
    Session.destroy({
      where: {
        expire_at: {
          lte: now
        }
      },
      logging: false
    }).then((count) => {
      if (count > 0) {
        logger.trace(`Removed ${count} expired sessions.`);
      }
    }).catch((e) => {
      logger.warn('Failed to perform session cleanup', e);
      logger.trace(e.message);
    }).finally(() => setTimeout(() => verifyExpiration(), CLEANUP_TIMER));
  }
1350286
public void removeSessions(PrimitiveId primitiveId) {
    sessions.entrySet().removeIf(e -> e.getValue().getService().serviceId().equals(primitiveId));
  }
604803
public ServiceCall<Void> deleteSession(DeleteSessionOptions deleteSessionOptions) {
    Validator.notNull(deleteSessionOptions, "deleteSessionOptions cannot be null");
    String[] pathSegments = { "v2/assistants", "sessions" };
    String[] pathParameters = { deleteSessionOptions.assistantId(), deleteSessionOptions.sessionId() };
    RequestBuilder builder = RequestBuilder.delete(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
        pathParameters));
    builder.query("version", versionDate);
    Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("conversation", "v2", "deleteSession");
    for (Entry<String, String> header : sdkHeaders.entrySet()) {
      builder.header(header.getKey(), header.getValue());
    }
    builder.header("Accept", "application/json");
    return createServiceCall(builder.build(), ResponseConverterUtils.getVoid());
  }
1364260
@Override
  public void cleanupSession(long sessionId) {
    Set<Long> blockIds;
    try (LockResource lr = new LockResource(mLock)) {
      blockIds = mSessionIdToBlockIds.get(sessionId);
      if (blockIds == null) {
        return;
      }
    }
    // Note that, there can be a race condition that blockIds can be stale when we release the
    // access. The race condition only has a minimal negative consequence (printing extra logging
    // message), and is expected very rare to trigger.
    for (Long blockId : blockIds) {
      try {
        // Note that we don't need to explicitly call abortBlock to cleanup the temp block
        // in Local block store because they will be cleanup by the session cleaner in the
        // Local block store.
        closeReaderOrWriter(sessionId, blockId);
        releaseAccess(sessionId, blockId);
      } catch (Exception e) {
        LOG.warn("Failed to cleanup UFS block {}, session {}.", blockId, sessionId);
      }
    }
  }
1354291
public void cleanupSession(long sessionId) {
    synchronized (mSharedMapsLock) {
      Set<Long> sessionLockIds = mSessionIdToLockIdsMap.get(sessionId);
      if (sessionLockIds == null) {
        return;
      }
      for (long lockId : sessionLockIds) {
        LockRecord record = mLockIdToRecordMap.get(lockId);
        if (record == null) {
          LOG.error(ExceptionMessage.LOCK_RECORD_NOT_FOUND_FOR_LOCK_ID.getMessage(lockId));
          continue;
        }
        Lock lock = record.getLock();
        unlock(lock, record.getBlockId());
        mLockIdToRecordMap.remove(lockId);
      }
      mSessionIdToLockIdsMap.remove(sessionId);
    }
  }
1286283
static function cleanup()
    {
        $http = eZHTTPTool::instance();

        $http->removeSessionVariable( 'CanInstantiateClassList' );
        $http->removeSessionVariable( 'ClassesCachedForUser' );

        // Note: This must be done more generic with an internal
        //       callback system.
        eZPreferences::sessionCleanup();
    }
233888
private static synchronized void cleanup() {
		int cleanedDirs = 0;
		int cleanedFiles = 0;
		// retrieve leftover swap directories
		File[] swapDirs = TMP_DIR.listFiles(new FileFilter() {
			public boolean accept(File pathname) {
				return pathname.getName().endsWith(SWAP_DIR_SUFFIX);
			}
		});
		for(File swapDir : swapDirs) {
			// check if swap directory is locked
			File lockFile = new File(TMP_DIR, swapDir.getName() + LOCK_FILE_SUFFIX);
			if(lockFile.exists() == false) {
				// no lock file, recursively delete leftover swap dir
				cleanedDirs++;
				cleanedFiles += deleteRecursively(swapDir);
			}
		}
		System.out.println("NikeFS2: cleaned up " + cleanedFiles + 
				" stale swap files (from " + cleanedDirs + " sessions).");
	}
1213040
public function handleClearSessions(): void
	{
		$this->checkHandlerPermission();

		$this->app->clearSession('0 minute');
		$this->flashNotifier->success('dockbar.management.application.sessionsCleared');
	}
889396
public function clear()
    {
        $now = Carbon::now('UTC');

        ORM::for_table('files_downloads')
            ->where_lt('created_at', $now->subHours(SettingsFile::TOKENS_OLDER_THAN_HOURS))
            ->delete_many();
    }
153807
@Override
	public void deleteSession(String sessionName) {
    	super.deleteSession(sessionName);
		logger.debug("deleteSession " + sessionName);

		deleteDbFile(new File(sessionName));
        deleteDbFile(new File(sessionName + ".data"));
        deleteDbFile(new File(sessionName + ".script"));
        deleteDbFile(new File(sessionName + ".properties"));
        deleteDbFile(new File(sessionName + ".backup"));
        deleteDbFile(new File(sessionName + ".lobs"));
    }
779474
function _endSession() {
        if (!hintList) {
            return;
        }
        hintList.close();
        hintList = null;
        codeHintOpened = false;
        keyDownEditor = null;
        sessionProvider = null;
        sessionEditor = null;
        if (deferredHints) {
            deferredHints.reject();
            deferredHints = null;
        }
    }
507117
def reap_expired_sessions
      @timestamps.each do |session_id,stamp|
        delete_session(session_id) if (stamp + @session_ttl) < Time.now 
      end
      GC.start
    end
228154
static function sessionCleanup()
    {
        $http = eZHTTPTool::instance();

        $valueList = array( self::AVAILABLE_ARRAY,
                            self::STEP,
                            self::USER_INFO,
                            self::LAST_CHECK_REDIRECT,
                            self::FORCE_LOGIN );

        foreach ( $valueList as $value )
        {
            if ( $http->hasSessionVariable( $value ) )
            {
                $http->removeSessionVariable( $value );
            }
        }

        $ini = eZINI::instance();
        $handlerList = array( 'standard' );
        if ( $ini->hasVariable( 'UserSettings', 'LoginHandler' ) )
        {
            $handlerList = $ini->variable( 'UserSettings', 'LoginHandler' );
        }

        foreach( $handlerList as $handler )
        {
            $loginHandler = eZUserLoginHandler::instance( $handler );
            if ( $loginHandler )
            {
                $loginHandler->sessionCleanup();
            }
        }
    }
132804
static function CleanUp()
	{
		$limit = new \DateTime('-30 minutes');
		foreach(self::$instances as $login => $player)
			if($player->awaySince && $player->awaySince < $limit) unset(self::$instances[$login]);
	}
41374
@Override
    final public void cleanup() throws ResourceException {

        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
            SibTr.entry(this, TRACE, "cleanup");
        }

        // Invalidate all of the sessions

        for (final Iterator iterator = _sessions.iterator(); iterator.hasNext();) {
            final Object object = iterator.next();
            if (object instanceof JmsJcaSessionImpl) {
                ((JmsJcaSessionImpl) object).invalidate();
            }
        }
        _sessions.clear();

        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
            SibTr.exit(this, TRACE, "cleanup");
        }

    }
367068
def clean_old_jobs():
    '''
    
    '''
    if __opts__.get('keep_jobs', False) and int(__opts__.get('keep_jobs', 0)) > 0:
        try:
            with _get_serv() as cur:
                sql = "select (NOW() -  interval '{0}' hour) as stamp;".format(__opts__['keep_jobs'])
                cur.execute(sql)
                rows = cur.fetchall()
                stamp = rows[0][0]

            if __opts__.get('archive_jobs', False):
                _archive_jobs(stamp)
            else:
                _purge_jobs(stamp)
        except Exception as e:
            log.error(e)
927741
public void closeSession(long index, long timestamp, RaftSession session, boolean expired) {
    log.debug("Closing session {}", session.sessionId());

    // Update the session's timestamp to prevent it from being expired.
    session.setLastUpdated(timestamp);

    // Update the state machine index/timestamp.
    tick(index, timestamp);

    // Expire sessions that have timed out.
    expireSessions(currentTimestamp);

    // Remove the session from the sessions list.
    if (expired) {
      session = sessions.removeSession(session.sessionId());
      if (session != null) {
        session.expire();
        service.expire(session.sessionId());
      }
    } else {
      session = sessions.removeSession(session.sessionId());
      if (session != null) {
        session.close();
        service.close(session.sessionId());
      }
    }

    // Commit the index, causing events to be sent to clients if necessary.
    commit();
  }